Basic Usage
Every CacheBox provider — whether it's the built-in CacheBoxProvider, a LuceeProvider, a BoxLangProvider, or your own custom implementation — shares the same core, cache-agnostic API defined by the ICacheProvider interface. This means you can swap out the underlying caching engine without changing a single line of your application code.
This page covers the essential methods you will use day to day: get(), set(), and most importantly, getOrSet().
Getting a Cache Reference
You always start by asking the CacheFactory for a named cache (or just grab the default one):
// The default cache
cache = cacheBox.getDefaultCache();
// Or a specific named cache
cache = cacheBox.getCache( "myCache" );get() / set()
The most basic operations are get() and set():
// Store an object for 20 minutes, with a 10 minute idle (last access) timeout
cache.set( "myKey", myComplexObject, 20, 10 );
// Retrieve it
myComplexObject = cache.get( "myKey" );If the key does not exist or has expired, get() returns an empty/null result. That means the typical caching pattern looks like this:
That pattern is so common that CacheBox gives you a single method that does it all for you, atomically: getOrSet().
getOrSet() — The Get-Or-Produce-And-Set Pattern
Method Signature
objectKey
any
true
The cache key to look up (and store to, if missing)
produce
any
true
A closure/UDF (no arguments) that is invoked only if the key is not found in the cache. Its return value is cached and returned
timeout
any
false
""
The timeout to use when storing the produced object (provider specific, usually minutes)
lastAccessTimeout
any
false
""
The idle/last-access timeout to use when storing the produced object (provider specific)
extra
any
false
{}
A struct of extra name-value pairs passed through to the provider's set() operation
How It Works
CacheBox first checks if
objectKeyalready exists in the cache. If it does, that value is returned immediately — yourproduceclosure is never called.If it does not exist, CacheBox acquires an exclusive lock scoped to that specific cache + key (so concurrent requests for the same missing key don't all stampede your data source at once).
Inside the lock, it double-checks the cache (in case another thread just produced it while you were waiting for the lock).
If it's still missing, it executes your
produceclosure, takes the result, stores it viaset()using thetimeout/lastAccessTimeout/extrayou provided, and returns it.
This effectively gives you cache stampede protection for free.
Usage Example
You can also pass extra provider-specific arguments via the extra struct:
Other Common Operations
For the full list of methods available on every provider (lookup(), clear(), clearAll(), bulk/multi operations, metadata retrieval, and more) see the ICacheProvider reference.
Last updated
Was this helpful?