Caching with Redis: Node.js Example

Ankit Kumar Rajpoot
2 min readOct 1, 2021

Now that you have an understanding of what Caching and Redis are, let’s build very basic implements caching using Redis. I will assume a beginner-level understanding of Node.js with Express.

In this example, I am using a different file for Redis set up and in this file, we will do a proper setup of Redis with Redis library and define some basic Redis functions to use these in your project.

const redis = require('redis');
const chalk = require("chalk");
// Redis setup
// create and connect redis client to local instance.
const client = redis.createClient(
{
host: '127.0.0.1',
port: 6379,
}
);
// Print ready msg to the console
client.on('ready', (err) => {
console.log(chalk.blue("Redis is successfully connected!!"));
});
// Print redis errors to the console
client.on('error', (err) => {
console.log("Redis Error " + chalk.red(err));
});
/**
* * this the method for get any key's value.
* @param redisKey
* @returns value
*/
module.exports.get = async (redisKey) => {
return client.get(redisKey, (err, result) => {
return result;
});
}
/**
* * this the method for set any key with the tts value.
* @param redisKey
* @param Value
* @param Ttl in mili seconds
* @returns true
*/
module.exports.set = async (redisKey, value, ttl) => {
if (ttl) {
client.set(redisKey, value, 'EX', ttl);
} else {
client.set(redisKey, value);
}
}

you can import this file anywhere inside your project and use functions.

// Import the file
const { get, set } = require("../../redis");
// Uses let bb = await set('key', "value", 30); let aaa = await get('key');

That’s it for this time! I hope you enjoyed this post. As always, I welcome questions, notes, comments and requests for posts on topics you’d like to read. See you next time! Happy Coding !!!!!

--

--

Ankit Kumar Rajpoot

I’m a MERN Developer. ( Redux | AWS | Python ) I enjoy taking on new things, building skills, and sharing what I’ve learned.