Connect NodeJS with Redis Cluster (Password protected)
What is Redis?
Redis (REmote DIctionary Server) is an open source, in-memory, NoSQL key/value store that is used primarily as an application cache or quick-response database.
Redis is often referred to as a data structures server. What this means is that Redis provides access to mutable data structures via a set of commands, which are sent using a server-client model with TCP sockets and a simple protocol. So different processes can query and modify the same data structures in a shared way.
Documentation Link: https://redis.io/docs/latest/
What is NodeJS?
Node.js is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools and scripts.
Documentation: https://nodejs.org/docs/latest/api/
How to connect NodeJS with Redis Cluster?
First we need to install Redis Cluster server in local machine. Please refer redis official documentation mentioned below for more details.
Secondly we need to install NodeJs in local Machine. Please refer documentation mentioned below for more details.
Please verify your installation using below mentioned command
NodeJS
Redis
Please refer below mention steps
STEP 1: Create a file named redis-cluster-connect.js
STEP 2: Download ioredis package
STEP 3: import redis dependency
const Redis = require("ioredis");
STEP 4: Now Connect with redis
const redis = new Redis.Cluster(
[
{
host: <IP>,
port: <PORT>
}, {
host: <IP>,
port: <PORT>
}, {
host: '<IP>',
port: '<PORT>'
}
],{
redisOptions: {
password: '<PSWD>'
}
}
);
you can pass multiple parameter. Please refer ioredis documentation
Now we can add data to redis. for example
redis.set("mykey", "value");
// Or ioredis returns a promise if the last argument isn't a function
redis.get("mykey").then((result) => {
console.log(result); // Prints "value"
});
// we can use async / await as well
await redis.get("mykey");
Conclusion
Now we have learned to connect nodeJS with redis cluster. Thanks for reading :)
If you like this article press 👏 the clap button 1000 times or as many times as you want. Feel free to ask a question if you have any. Thanks a lot for reading!
Before You Go
Thanks for reading! If you want to get in touch with me, feel free to reach me at gauravrathee0@gmail.com or my LinkedIn Profile. Also, feel free to explore my profile and read different articles.