How can I use the same RedisCluster connection throughout the app in NestJs?

397 Views Asked by At

I am using NestJs and have created a Redis Module and a Bull Module.I want to define the Redis Cluster connection in the RedisModule and use the same connection for Bull as well as Cache Manager etc.How can I achieve the same?

redis.module.ts

import { Module, Global } from '@nestjs/common';
import { Cluster, Redis } from 'ioredis';
import { RedisService } from './redis.service';
import { CacheModule } from '@nestjs/cache-manager';
import * as redisStore from 'cache-manager-ioredis';

@Global()
@Module({
    providers: [{
        provide: 'REDIS_CLUSTER',
        useFactory: async (): Promise<Cluster> => {
            return new Redis.Cluster([
                {
                    host: process.env?.REDIS_HOST,
                    port: process.env?.REDIS_PORT
                        ? Number(process.env?.REDIS_PORT)
                        : 6379,
                },
            ], {
                enableAutoPipelining: true,
                redisOptions: {
                    ...(process.env?.REDIS_PASSWORD && {
                        password: process.env.REDIS_PASSWORD,
                    }),
                    maxRetriesPerRequest: null,
                    enableReadyCheck: false,
                },
            });
        }

    },RedisService],
    exports: ['REDIS_CLUSTER', RedisService],
})
export class RedisModule { }

bull.module.ts

import { Logger, Module } from '@nestjs/common';
import { BullModule, BullModuleAsyncOptions } from '@nestjs/bull';
import Redis from 'ioredis';

@Module({
  imports: [
    BullModule.forRootAsync({
      inject: ['REDIS_CLUSTER'],
      useFactory: (client) => ({
         // Code for same connection?
        },
      }),
    }),
  ],
})
export class BullModule { }
0

There are 0 best solutions below