DEV Community

Cover image for Redis Singleton in Your Express Application
hoangbui
hoangbui

Posted on • Updated on

Redis Singleton in Your Express Application

Hi guys !!!
Are you looking to optimize your Express application with efficient Redis usage? Look no further! In this post, we'll dive into implementing a Redis Singleton in your Express app to ensure a streamlined, efficient, and scalable caching solution. Let's enhance our applications together!

To create a Redis connection that is initialized once and reused throughout your Node.js Express application, you can use a singleton pattern. This ensures that only one instance of the Redis client is created and shared across different parts of your application.

1. Install Redis Client: First, make sure you have the Redis client library installed. You can use ioredis or redis. Here, we'll use ioredis.
npm install ioredis

2. Create a Redis Singleton Class:

// redisClient.js
const Redis = require('ioredis');

class RedisClient {
  constructor() {
    if (!RedisClient.instance) {
      this.client = new Redis({
        host: 'localhost', // Change to your Redis server host
        port: 6379,        // Change to your Redis server port
        // Add other Redis connection options if necessary
      });

      this.client.on('connect', () => {
        console.log('Connected to Redis');
      });

      this.client.on('error', (err) => {
        console.error('Redis error', err);
      });

      RedisClient.instance = this;
    }

    return RedisClient.instance;
  }

  getClient() {
    return this.client;
  }
}

const instance = new RedisClient();
Object.freeze(instance);

module.exports = instance;

Enter fullscreen mode Exit fullscreen mode

3. Use the Redis Singleton in Your Express Application:

// app.js
const express = require('express');
const redisClient = require('./redisClient');

const app = express();
const port = 3000;

app.get('/', async (req, res) => {
  const client = redisClient.getClient();
  await client.set('key', 'value');
  const value = await client.get('key');
  res.send(`Value for 'key' is: ${value}`);
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Enter fullscreen mode Exit fullscreen mode

Following this strategy ensures that just one Redis client instance is created and reused throughout your application, making it more efficient and reducing the number of needless connections to the Redis server.

Try it <3 Happy coding!!!

Top comments (0)