Redis in Node JS

Issam Eddine Bouhoush
3 min readSep 27, 2023

--

What’s Redis:

Redis is an open-source, real-time in-memory database management system (DBMS). The name “Redis” is an abbreviation of “Remote Dictionary Server”. It was created by Salvatore Sanfilippo and is widely used to store and manage data in memory, making it a popular option for many applications requiring minimal latency and high performance.

Redis is commonly used in web applications, caching systems, message queues, real-time online gaming, real-time analytics, recommendation systems, and many other applications that require manipulation of fast data in memory. It is available as open source and has numerous client libraries for many programming languages, making it easy to integrate into various applications.

Here are some key features of Redis:

. In-memory storage: Redis stores all data in RAM, which allows very fast read and write operations. This makes it an ideal choice for caches, real-time web sessions, real-time dashboards, etc.

. Data structure: Redis supports a variety of data structures, including strings, lists, sets, dictionaries, sorted sets, hyperloglogs, bitmaps, and more. This makes it versatile for a wide range of use cases.

. Persistence: Although Redis stores data in memory, it provides persistence options to periodically save data to disk, allowing data to be recovered in the event of a server crash or restart.

. High availability: Redis supports replication, which allows you to have copies of data on multiple servers. It also offers automatic failover mechanisms in the event of master node failure.

. Extensibility: Redis can be extended using modules, allowing you to add new features and customize its behavior.

. Pub/Sub: Redis supports publishing and subscribing (Pub/Sub), which enables the implementation of real-time messaging and delivery systems.

. High Performance: Redis is known for its high performance due to its in-memory storage and optimized architecture.

Simple example of using Redis with Express.js:

Here’s a simple example of using Redis with Express.js, a popular JavaScript framework for building Node.js web applications. In this example, we will create an Express application that uses Redis to temporarily store data in memory.

First, make sure you have Redis installed and running on your system.

Then you can create an Express.js project and install the Redis Node.js ioredis package via npm or yarn if you haven’t already:

npm install express ioredis

. Example Express.js application that uses Redis to store and retrieve data in memory:

const express = require('express');
const Redis = require('ioredis');

const app = express();
const redis = new Redis();

// Middleware pour parser le corps des requêtes en JSON
app.use(express.json());

// Route pour stocker des données en Redis
app.post('/set', async (req, res) => {
const { key, value } = req.body;

// Utilise Redis pour stocker la valeur
await redis.set(key, value);

res.send('Données stockées en Redis');
});

// Route pour récupérer des données depuis Redis
app.get('/get/:key', async (req, res) => {
const { key } = req.params;

// Utilise Redis pour récupérer la valeur
const value = await redis.get(key);

if (value) {
res.json({ key, value });
} else {
res.status(404).send('Clé introuvable');
}
});

app.listen(3000, () => {
console.log('Serveur Express en cours d\'exécution sur le port 3000');
});

In this example, we create an Express.js application with two routes:

POST /set: This route allows you to store data in Redis. The client can send a POST request with a key and a value, and this data is then stored in Redis using the Redis set method.

GET /get/:key: This route allows you to retrieve data from Redis by specifying a key in the URL. The corresponding value is retrieved using the Redis get method and returned to the client.

You can test this example using a REST client such as Postman or by making HTTP requests from your browser. Make sure Redis is running before launching this application.

“Thank you for reading this article. See you soon!”

--

--