Introduction to Redis in Nodejs
Redis is an in-memory data store that acts as a data distrubitor, cache, key-value database and so on. Personally, I have used Redis as a cache between containers to share data. Example, if you have a GCP Cloud Run service where you store cached data, and Google spins up multiple containers due to high load of requests for example - the container in-memory data will not be shared between the containers, hence, a Redis cache is a perfect way of solving issues like this. Since the Redis cache is hosted on a different server, all containers that are reading/writing will gain access of the same data.
In todays tutorial, we will setup a Redis server and then add and read data from it, using NodeJs. We will create a requestCounter which are counting all our requests, we will also setup an endpoint that will reset the counter and finally one that are flushing the whole cache.
Create Redis free account (optional)
If you haven't any redis server up and running, they offer 30 mb of free data with an easy sign up. Navigate to redis to sign up and set up your free database.
Install redis locally (optional)
If you prefer running it locally, and don't have any plans of deploying your application to any live server, we can download it locally as well. Download is available here.
Implementation
Let's first install redis package with npm (and express).
npm i redis express
And if you downloaded redis locally, start the server with this command.
redis-server
Let's write some code
In our server, let's setup our redis client and connect to it.
const redis = require("redis"); const redisClient = redis.createClient({ url: "redis://localhost:6379" }); redisClient.connect();
And now, we should be good to go to start using our cache.
Count requests
We will start with one endpoint that we want to increment the cache.
app.get("/ping", async (req, res) => { const count = await redisClient.incr("requestCounter"); res.json({ requestCount: count }); });
So for each GET /ping, our requestCounter will increment by one, and finally we are sending the current count to the client.
Set cache value to 0
To demonstrate how we can set a value, we will do another endpoint that will set the count to 0.
app.get("/reset", (req, res) => { redisClient.set("requestCounter", 0); res.send("Done resetting requestCounter"); });
By using set function, we specify which key we want to change, and then second parameter is the new value.
Flushing cache
If you for some reason want to flush the whole cache, redis have support for this as well. Let's create another endpoint that will flush the cache.
app.get("/flush", (req, res) => { redisClient.flushAll(); res.send("Cache is flushed"); });
Get value
If we want to read a specific value from the cache, this is how we can access it using the get function.
app.get("/cache/:key", async (req, res) => { const { key } = req.params; const cache = await redisClient.get(key); res.send({ [key]: cache }); });
Full code
const express = require("express"); const redis = require("redis"); const redisClient = redis.createClient({ url: "redis://localhost:6379" }); redisClient.connect(); const app = express(); app.get("/ping", async (req, res) => { const count = await redisClient.incr("requestCounter"); res.json({ requestCount: count }); }); app.get("/reset", (req, res) => { redisClient.set("requestCounter", 0); res.send("Done resetting requestCounter"); }); app.get("/flush", (req, res) => { redisClient.flushAll(); res.send("Cache is flushed"); }); app.get("/cache/:key", async (req, res) => { const { key } = req.params; const cache = await redisClient.get(key); res.send({ [key]: cache }); }); app.listen(3005, function () { console.log("Web server listening on port 3005"); });
Try it out
So, now we can start playing around with our cool cache. If we start our server, we can test our endpoints.
GET /ping
{ "requestCount": 1 }
Calling GET /ping will give us a new value for every time we do a request.
GET /reset
Done resetting requestCounter
GET /cache/requestCounter
{ "requestCounter": "0" }
GET /flush
Cache is flushed
Outro
Today, we briefly looked at how we can use Redis as a cache in our NodeJs application by setting up a local server. If you want to connect to your remote redis server, simply change the url in redis.createClient({ url }) to the url provided by redis.
Redis offers a wide range of powerful features, such as pub/sub for subscribing to cache changes. We will cover more advanced features in the near future, so stay tuned.
Hope you enjoyed this guide, and thanks for reading!