要在 NestJS 中使用 Redis,需要安装依赖npm install --save redis fastify-redis
在 app.module.ts
中导入 RedisModule
和 CacheModule
:
import { Module } from '@nestjs/common';
import { RedisModule } from 'nestjs-redis';
import { CacheModule } from '@nestjs/common';
@Module({
imports: [
RedisModule.register({
host: 'localhost', // Redis 服务器地址
port: 6379, // Redis 服务器端口号
password: 'your_password', // Redis 密码(如果需要)
}),
CacheModule.register(),
],
})
export class AppModule {}
创建一个使用 Redis 的服务示例:
import { Injectable, Inject } from '@nestjs/common';
import { Redis } from 'ioredis';
import { CACHE_MANAGER } from '@nestjs/common';
@Injectable()
export class RedisService {
constructor(
@Inject(CACHE_MANAGER) private cacheManager: CacheManager,
@Inject('REDIS') private readonly redis: Redis,
) {}
async setValue(key: string, value: any) {
await this.cacheManager.set(key, value);
}
async getValue(key: string): Promise<any> {
return await this.cacheManager.get(key);
}
async removeFromCache(key: string) {
await this.cacheManager.del(key);
}
}
使用 Redis 服务:
import { Controller, Get, Param } from '@nestjs/common';
import { RedisService } from './redis.service';
@Controller('example')
export class ExampleController {
constructor(private readonly redisService: RedisService) {}
@Get('set/:key/:value')
async setKeyValue(
@Param('key') key: string,
@Param('value') value: string,
): Promise<void> {
await this.redisService.setValue(key, value);
}
@Get('get/:key')
async getValueByKey(@Param('key') key: string): Promise<any> {
return await this.redisService.getValue(key);
}
@Get('remove/:key')
async removeFromCache(@Param('key') key: string): Promise<void> {
await this.redisService.removeFromCache(key);
}
}
以上步骤中,我们使用 nestjs-redis
模块提供的 RedisModule
来连接和配置 Redis。在 RedisService
中,我们使用 CACHE_MANAGER
标记注入缓存管理器,并通过 REDIS
标记注入 Redis 实例。
在 ExampleController
中,我们使用 RedisService
来展示如何设置、获取和删除缓存数据。需要了解更多 Redis 操作,请参考 Redis 官方文档:https://redis.io/documentation。