When we talk about the centralized caching mechanism. The first option that comes to mind is Redis. Because Redis cache is compatible with a wide range of programming languages, including Nodejs, C#, Java, Python, and PHP. This article will go over a working example of setting Redis for the node js application.

We just need to follow 3 Stesps to Setup Redis for Node Js Application

  • Install Redis Server
  • Setup Project and Install npm package
  • Create Connection with Redis Server

Install Redis Server

In order to set up Redis for node js, we need to make sure the Redis server is up and running on your machine. Else, you can follow the listed articles to setup Redis.

Redis in Windows

Redis in Linux Machine

Redis as Docker Container

Setup Project & Install npm package

You can use any IDE for code. I will be using VS Code as a code editor for this demo. Start with creating a folder and index.js file inside the folder. I have created a RedisDemo/Index.js.

redis for caching using node js

Install the Redis npm package by issuing a command.

npm install redis

Once the package installation is done. Open the index.js file and start following the steps.

Create Connection with Redis Server

var redis = require('redis');
var client = redis.createClient(); 

Use createClient method to connect to the Redis server. By default, it will take the address of server localhost and default port 6379 as a parameter.

To connect with the Redis server installed in different machines. Pass the Ip address and port as a parameter. I am going to use the Redis server installed in Linux Machine. So, I have to pass both the parameters.

var client = redis.createClient('6379', '192.168.1.108');

Validate the connection by using a connected event. Which will be triggered when the server is connected successfully.

client.on('connect', function () {
    console.log('connected');
});

Console Out

redis client test

As you can see in the above image. The connection has been established successfully for me. Now, lets start with basic operations which we can perform with Redis. As we know Redis is a Key value pair database. So, Every operation will do should be in that format.

How to set and get the string in Redis?

The most common data types are used in any language in the string. Let see how we can store and retrieve this in Redis.

Set string, set function in Redis
client.set('Application', 'I am NodeJS Client');

It will store “Application” as key and “I am NodeJS Client” as the value in the Db.

Get string,get function in Redis.
client.get('Application', function(err, reply) {
    console.log(reply);
});

We need to pass key as the first parameter and a callback function as the second is a parameter that will hold the response from the Redis server.

Manage list in Redis

There are several ways a value can be added to a Redis List.

  • The LPUSH command adds value to the head of a Redis list.
  • The RPUSH command adds value to the tail of a Redis list.  The time complexity is O(1).
  • The LINSERT command adds value before or after the first occurrence of a specific value.
  • The LSET command sets a value for the element specified by the index.
rpush in Redis
client.rpush(['Countries', 'India', 'US','UK']);

In the above function, the first value will be the key which is “Countries” and the remaining values will be the value corresponding to the key.

rpop in Redis

rpop function, Removes and returns the last element of the list stored at key.

client.rpop('Countries', function (err, reply) {
    console.log(reply);
});

The above function will return the last element of the list and remove the element. The output should be like.

Console Out

$ node Index.js
UK
Set Dictionary, how to use hmset in Redis?
user = {"Name":"DK", "Mobile":"123456789", "Address":"Delhi", "Location":"TML"}
conn.hmset("myAddress", user)

you can use hmset function to store the multiple keys into the Redis.

Get Dictionary, how to use hgetall in Redis?
client.hgetall('myAddress', function (err, results) {
    console.log(results);
});

Console Out

$ node index.js
{ Name: 'DK', Mobile: '123456789', Address: 'Delhi', Location: 'TML' }

How to manage sets in Redis

set is a data structure that can store any number of unique values in any order you so wish. Set’s are different from arrays in the sense that they only allow non-repeated, unique values within them.

Store sets,sAdd function in Redis

we can use sAdd function to add sets of data in Redis.

client.sadd('Contacts', '8895869587','5986792589','5682648965');

If you want to validate wheather the operation is successful or not. you can pass the last parameter in the function to get the response from Redis. You will get either one or zero indicating success or failure.

client.sadd('Contacts', '88958695803', function (err, results) {
    console.log(results);
});

As you can see in the above piece of code, Contacts sets do not have the value 88958695803, So we should get 1 as a response.

Console Out

 $ node index.js
1

If you try to add the same value again in the sets, you should receive 0. Indicating operation failure.

Console Out

 $ node index.js
0
get sets, by using smembers, srandmember and spop function in Redis.

There are many functions that can be used to retrieve the set’s value.

srandmember

As the name suggests this function can be used to retrieve some random value stored in the sets collection.

client.srandmember('Contacts', function (err, reply) {
    console.log(reply);
});

The console Out

$ node index.js
5682648965
smembers

function gives you the entire collection.

client.smembers('Contacts', function (err, reply) {
    console.log(reply);
});

Console Out

$ node index.js
[ '5682648965', '5986792589', '8895869580', '8895869587' ]
spop

Redis SPOP function is used to remove and return a random member from the set stored at a specified key.

client.spop('Contacts', function (err, reply) {
    console.log(reply);
});

Console Out

$ node index.js
8895869580

There are many other options available that can be explored in the Redis official documentation.

https://redis.io/documentation

How to set and get the json data in Redis?

Set Json value

The easiest way to store complex json data in Redis is to convert json into a string and store it using the set function.

var jsondata = {
    "Name": "DK",
    "Mobile": "8958965895",
    "Address": {
        "Country": "India",
        "City": "Bangalore"
    }
};
var jsonAsString = JSON.stringify(jsondata);
client.set('EMP01', jsonAsString, function (err, reply) {
    console.log(reply);
});
get json value

Since we have stored the json data as a string. We can use simple get the function to retrieve the json object and parse using JSON. Parse method.

client.get('EMP01', function (err, reply) {
    var stringAsJson = JSON.parse(reply);
    console.log(stringAsJson);
});

Console Out

$ node index.js
{
  Name: 'DK',
  Mobile: '8958965895',
  Address: { Country: 'India', City: 'Bangalore' }
}

https://github.com/dkushwah/RedisWithNodeJsDemo

Wrapping it up!

So, in this article, we came to know about different functions availble in the npm Redis library. How to manage different data types in the Redis server. Also, how to create a connection with local or remote Redis servers.

83 / 100

5 Comments

Comments are closed