在 NestJS 中使用 Redis 通常涉及以下步骤:
- 安装依赖:
首先,你需要安装 Redis 客户端库。可以使用redis
或ioredis
库。
npm install redis
- 配置 Redis 客户端:
在cache.module.ts
中,使用createClient
方法创建 Redis 客户端,并通过ConfigService
读取 Redis 的配置信息。
import { Module } from '@nestjs/common';
import { CacheService } from './cache.service';
import { CacheController } from './cache.controller';
import { ConfigService, ConfigModule } from '@nestjs/config';
import { createClient } from 'redis';
@Module({
imports: [ConfigModule],
controllers: [CacheController],
providers: [CacheService,
{
provide: 'REDIS_CLIENT',
useFactory: async (configService: ConfigService) => {
const client = createClient({
socket: {
host: configService.get('REDIS_HOST', 'localhost'),
port: configService.get('REDIS_PORT', 6379),
},
password: configService.get('REDIS_PASSWORD'),
database: configService.get('REDIS_DB', 0),
});
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
return client;
},
inject: [ConfigService]
}
],
exports: [CacheService]
})
export class CacheModule { }
- 注入 Redis 客户端:
在cache.service.ts
中,通过@Inject
装饰器注入 Redis 客户端,并在服务中使用它。
import { Inject, Injectable } from '@nestjs/common';
import { RedisClientType } from 'redis';
@Injectable()
export class CacheService {
@Inject('REDIS_CLIENT')
private readonly redis: RedisClientType;
async setRedis(key: string, value: string, time?: number) {
return await this.redis.set(key, value, { EX: time });
}
async getRedis(key: string) {
return await this.redis.get(key);
}
async delRedis(key: string) {
return await this.redis.del(key);
}
}
- 使用 CacheService:
在其他模块中,你可以通过注入CacheService
来使用 Redis 的功能。
import { Injectable } from '@nestjs/common';
import { CacheService } from '../common/cache/cache.service';
@Injectable()
export class UserService {
constructor(private readonly cacheService: CacheService) {}
async someMethod() {
await this.cacheService.setRedis('key', 'value', 60); // 设置缓存
const value = await this.cacheService.getRedis('key'); // 获取缓存
await this.cacheService.delRedis('key'); // 删除缓存
}
}
- 配置环境变量:
在.env
文件中配置 Redis 的连接信息。
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=yourpassword
REDIS_DB=0
通过以上步骤,你可以在 NestJS 中成功集成并使用 Redis。