lock_and_cache
Lock and cache using Redis!
Most caching libraries don't do locking, meaning that >1 process can be calculating a cached value at the same time. Since you presumably cache things because they cost CPU, database reads, or money, doesn't it make sense to lock while caching?
Quickstart
; ; ; // If you forget this, your process will never exit.cache.close;
Install
npm install --save lock_and_cache
Theory
lock_and_cache...
- returns cached value (if exists)
- acquires a lock
- returns cached value (just in case it was calculated while we were waiting for a lock)
- calculates and caches the value
- releases the lock
- returns the value
As you can see, most caching libraries only take care of (1) and (4) (well, and (5) of course).
Setup
By default, you probably want to put locks and caches in separate databases:
export CACHE_URL=redis://redis:6379/2export LOCK_URL=redis://redis:6379/3
API
We have full JSDoc for this library, but these are the highlights at the time of writing.
/** * Valid cache keys. * * These may only contain values that we can serialize consistently. */; /** Options that can be passed to `get` and `wrap`. */; /** * A user-supplied function that computes a value to cache. * * This function may have an optional `displayName` property, which may be used * as part of the cache key if this function is passed to `wrap`. * * By default, `WorkFn` functions do not accept arguments, but if you're using * the `wrap` feature, you may want to supply an optional argument list. */;
Contributing
Please send us your pull requests!