feat: add redis

This commit is contained in:
Sergey Krylov 2026-01-24 14:30:19 +03:00
parent 4992f5651e
commit 62b06982ae
2 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,10 @@
import { Global, Module } from '@nestjs/common'
import { RedisService } from './redis.service'
@Global()
@Module({
providers: [RedisService],
exports: [RedisService]
})
export class RedisModule {}

View File

@ -0,0 +1,64 @@
import {
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import Redis from 'ioredis'
@Injectable()
export class RedisService
extends Redis
implements OnModuleInit, OnModuleDestroy
{
private readonly logger = new Logger(RedisService.name)
public constructor(private readonly configService: ConfigService) {
super({
username: configService.getOrThrow<string>('REDIS_USERNAME'),
host: configService.getOrThrow<string>('REDIS_HOST'),
port: configService.getOrThrow<number>('REDIS_PORT'),
password: configService.getOrThrow<string>('REDIS_PASSWORD'),
maxRetriesPerRequest: 5,
enableOfflineQueue: true
})
}
public onModuleInit() {
const start = Date.now()
this.on('connect', () => {
this.logger.log('Redis connecting...')
})
this.on('ready', () => {
this.logger.log(`Redis connected in ${Date.now() - start}ms`)
})
this.on('error', e => {
this.logger.error('Redis connection error', {
error: e.message || e
})
})
this.on('close', () => {
this.logger.warn('Redis connection closed')
})
this.on('reconnecting', () => {
this.logger.log('Redis reconnecting')
})
}
public async onModuleDestroy() {
this.logger.log('Redis disconnecting...')
try {
await this.quit()
this.logger.log('Redis disconnected')
} catch (e) {
this.logger.error('Redis disconnecting error', e)
}
}
}