Files
psp_api/src/redis/redis.service.ts
T

41 lines
961 B
TypeScript
Raw Normal View History

2026-05-19 09:14:30 +03:30
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()
}
}