Node.js and Redis Tutorial
In this Node.js tutorial, we will learn about Redis and how to use it with Node.js.
What is Redis?
Redis is an in-memory data store, meaning it stores data within the RAM for quick access. It’s typically used for caching frequently queried data, for eg: something like user-session information. Other than this it can also be used as a message broker or as temporary storage.
Storing data in-memory means the data is lost in case of server reboot unless we enable persistence in Redis. This is enabled by default. Redis supports a number of data-structures like strings, hashes, sets, lists, etc.
All these benefits combined with easy use makes Redis one of the popular in-memory datastore. Redis also works really well with Node.js and there are a number of client’s written for node.js and Redis.
Installing Redis – Linux
sudo apt-get install redis-server
sudo systemctl enable redis-server.service
To start the server run…
To run as a service in background
To check if Redis is properly installed and running…
When your type ping is should return PONG.
Using Redis with Node.js
To use Redis with node.js we need a Node.js client. We can install it by running…
By default, Redis runs on PORT-6379, unless specified something else. Now create a new file app.js and open it in your text editor.
const client = redis.createClient(6379, 'localhost');
On running the app it should say, ‘redis connected’. If it doesn’t then check if Redis server is running. To catch any errors, add the listener to error event.
If the Redis installation is password protected, we can pass the password as options while connecting.
Now that we have seen how to connect to Redis, let’s try and store some data into it.
Redis uses SET command to store data and GET command to retrive data.
Let’s see it in action.
To store a string as key-value pair…
To retrieve a key-value…
console.log(reply); //prints 2
The above command creates a list called food and pushes 2 values into it. As you can see we are using rpush command which will push new elements from the right, similarly we can use lpush to push elements from the left.
To retrieve all the elements from the list we can use the lrange command.
console.log(reply); // ['pasta', 'Noodles']
Note we pass -1 as the 3rd argument to retrieve all the elements, or we can pass a specific index to only get values up to that index.
To store an object we can use the hmset method.
We can retrieve this by using…
Alternatively, in Node.js we can also store the entire object, as a string using the set function.
Then we will need to parse the string when we retrieve it.
One other really useful feature of Redis is its ability to have temporary keys. This is particularly useful for storing session information.
The above code snippet will set key1 with an expiry time of 30 sec.
Common Interview Questions
Now that we know how to use Redis with node.js let’s see a few questions related to Redis you might be asked in an interview.
What is Redis and what is its use case?
This is the most important question and usually, the first question apart from (Have you worked with Redis?) you will be asked. We have already answered this at the start of this article.
How can Redis be used as a Message Broker?
Redis provides pub/sub mechanism which allows publishers to publish messages into a channel and subscribers to subscribe to one or more message channels.
Publishers and Subscribers work independently of one another, where a publisher will not know about the subscribers subscribing to a channel and vice-versa. This decoupling of pubs and subs allows Redis to achieve greater scalability.
Do we lose Redis data on shutdown? If yes how can we avoid it?
Redis works fast by storing data in-memory, and typically server shutdown means loss of in-memory data. However, Redis can be configured to persist data to disk and restore.
What are some of the Data Types supported by Redis?
- Hashes (Objects)
- Lists (Similar to arrays)
- Sorted Sets
In this Node.js Redis Tutorial, we saw how we can install Redis and use it with Node.js. We also learned it’s use cases and had a look at some of the related interview questions.
I hope this article benefited you in one way or another and you take away some learning points from the same. Feel free to share it if you love it.