set redis

This commit is contained in:
2026-05-19 09:14:30 +03:30
parent 758bb03a26
commit c5c522f69c
7 changed files with 213 additions and 61 deletions
+9
View File
@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common'
import { RedisService } from './redis.service'
@Global()
@Module({
providers: [RedisService],
exports: [RedisService],
})
export class RedisModule {}
+40
View File
@@ -0,0 +1,40 @@
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'
import Redis from 'ioredis'
@Injectable()
export class RedisService implements OnModuleDestroy {
private readonly logger = new Logger(RedisService.name)
private readonly client: Redis
constructor() {
const host = process.env.REDIS_HOST || 'redis'
const port = Number(process.env.REDIS_PORT || 6379)
const password = process.env.REDIS_PASSWORD || undefined
const db = Number(process.env.REDIS_DB || 0)
this.client = new Redis({
host,
port,
password,
db,
lazyConnect: true,
maxRetriesPerRequest: 3,
})
this.client.on('error', (error) => {
this.logger.error(`Redis error: ${error.message}`)
})
}
async getClient(): Promise<Redis> {
if (this.client.status !== 'ready') {
await this.client.connect()
}
return this.client
}
async onModuleDestroy() {
await this.client.quit()
}
}