Using Redis for Caching in Node.js
Your web service is slow and you want to store things into memory for cache. Luckily, it’s pretty easy to do this in your Node.js Express application.
First you want to install your Redis module from npm. Also make sure to edit your
package.json with the appropriate module and its version.
Then include it in the file where your caching your data. You usually want to put this in your “controller” or whatever is handling the requests to the client. Normally, we will put the Redis cache before your
Next you want to connect your Redis module to something useful and create your handler. I normally use Nodejitsu so I access the environment variables. It should be something similar to Heroku or any service you use, just make sure you set the environment variables or change the code to something it’ll connect to properly.
When a request comes in, we want to check if we have a response already prepared for them in Redis. To do so, we apply the following code. Don’t worry about expiration yet, that is covered when we set the actual data.
Basically what this does is ask Redis for data given for the key. Make you’re key unique to the request. Normally what I’d do stack all the parameters together and
sha1 them together, that way I have a unique key that I can rebuild and request later on. For example, if my request depends on a zipcode, I’ll be making my key exactly the zipcode. If the key does not contain any data, we’ll execute our function that normally generates this data. In this case
execute_function will be the function I will call.
Last, we need to store the compiled data, note that we’re passing a
handler function over to our executed function,
execute_function. We’re now gonna replace that function to something that stores to Redis.
.setex which means set value and expire after ‘X’ seconds. In this case, based on the key I created, I stored a value of
response that will expire in 6 hours or 21600 seconds. Now because its set in Redis, my
client.get function will capture and return data and instead respond directly with the data retrieved from Redis. After 6 hours, this data will expire in Redis and return nothing to the
client.get function resulting in needing to re-run
handler when it is complete and restore the data.