Skip to content

Instantly share code, notes, and snippets.

@saurabh-vt
Created March 8, 2024 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saurabh-vt/e027ce57bfa3897d16bcb4888b553ad4 to your computer and use it in GitHub Desktop.
Save saurabh-vt/e027ce57bfa3897d16bcb4888b553ad4 to your computer and use it in GitHub Desktop.
import { CacheModule as DefaultCacheModule } from '@nestjs/cache-manager';
import { Module } from '@nestjs/common';
import { redisStore } from 'cache-manager-ioredis-yet';
import type { RedisOptions } from 'ioredis';
import { RedisModule } from '../redis/redis.module';
import { RedisService } from '../redis/redis.service';
@Module({
imports: [
DefaultCacheModule.registerAsync<RedisOptions>({
imports: [RedisModule],
inject: [RedisService],
useFactory: (redisService: RedisService) => ({
redisInstance: redisService.getClient(),
store: redisStore,
}),
}),
],
})
export class CacheModule {}
import { Global, Module } from '@nestjs/common';
import { RedisService } from './redis.service';
@Global()
@Module({
providers: [RedisService],
exports: [RedisService], // Export RedisService so it can be used in other modules
})
export class RedisModule {}
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import Redis from 'ioredis';
@Injectable()
export class RedisService implements OnModuleInit, OnModuleDestroy {
private readonly client: Redis;
constructor() {
this.client = new Redis({
host: 'localhost', // Redis host
port: 6379, // Redis port
username: 'username',
password: 'password',
connectionName: 'qqqqqqqqqq',
});
}
onModuleInit() {
this.client.on('connect', () => {
console.log('Connected to Redis');
});
}
onModuleDestroy() {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.client.quit(() => {
console.log('exit');
});
}
getClient(): Redis {
return this.client;
}
// You can add more methods to interact with Redis as needed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment