feat: add redis
This commit is contained in:
parent
4992f5651e
commit
62b06982ae
10
src/infra/redis/redis.module.ts
Normal file
10
src/infra/redis/redis.module.ts
Normal 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 {}
|
||||
64
src/infra/redis/redis.service.ts
Normal file
64
src/infra/redis/redis.service.ts
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user