existence-cache v1.0.2
existence-cache
An NPM package that uses either ElastiCache or local memory to set and check for the existence of keys
Installation
npm install existence-cache
Usage
You set up configuration when requiring the module.
The parameters it accepts being: (elasticache_endpoint, elasticache_port, horribleErrorFunc)
, where:
elasticache_endpoint
(Optional) - Endpoint for a Redis-based ElastiCache clusterelasticache_port
(Optional) - Port for the cluster, defaults to 6379horribleErrorFunc
(Optional) - Function to call if it cannot connect to the cache (ElastiCache or in local memory)- Will run
horribleErrorFunc(message, error)
upon a horrible error if a function is provided.
- Will run
If elasticache_endpoint
is not specified, this will default to caching using local memory.
Require it like this:
var cache = require('existence-cache')('somecluster.abcde.0001.usw2.cache.amazonaws.com', 6000, postSNSAlert);
or just like:
var cache = require('existence-cache');
Then, use it like this:
cache.set("key", 20);
cache.check("key");
Where cache.set
behaves as a synchronous function and its parameters are
key
- A unique stringttl
- (Optional) Time to live, in seconds.0
will permanently set the key, negative values will delete it.Defaults to permanently setting the key.
And cache.check
behaves as an asynchronous function and has the parameter:
key
- A unique string to check if it exists (has been set in the cache and not expired)
Example
var cache = require('existence-cache')(null, null, console.error);
cache.check("15")
.then(function(){
console.log("Setting the key in the cache.");
return Promise.resolve(cache.set("15", 1));
})
.then(function(){
console.log("Made it here!");
return Promise.resolve(cache.check("15"));
})
.then(function(){
console.log("This code doesn't run, since 15 was in the cache.");
})
.catch(console.log);
###Some Notes about ElastiCache The ElastiCache functionality only works with Redis-based ElastiCache Clusters.
ElastiCache is only accessible from an EC2 instance (whether you start that instance directly, or through Elastic Beanstalk).
When setting up your clusters, be sure they are in the same VPC as your EC2 instance(s) and that the security group has the appropriate inbound rule to allow access to ElastiCache.
For further reference, see Amazon's documentation.