set redis
This commit is contained in:
@@ -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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user