cache-manager 6.x版本中,原来的cache-manager-redis-yet将被弃用,转为使用@keyv/redis

使用方法:


1. 先安装依赖,其中cache-manager升级到最新,@nestjs/cache-manager升级到next版本



pnpm add keyv
pnpm add @keyv/redis
pnpm add cache-manager
pnpm add @nestjs/cache-manager@next


2. app.module.ts


import KeyvRedis, { Keyv } from '@keyv/redis';
import { CacheModule } from '@nestjs/cache-manager';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';

// 环境变量加载
const envFilePath = ['.env'];
if (process.env.NODE_ENV) {
envFilePath.unshift(`.env.${process.env.NODE_ENV}`);
}

@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath,
}),
CacheModule.registerAsync({
isGlobal: true,
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => {
const host = configService.get<string>('REDIS_HOST');
const port = configService.get<number>('REDIS_PORT');
const redisPass = configService.get<string>('REDIS_PASS');

const redisOptions = {
url: `redis://${host}:${port}/0`, // The Redis server URL (use 'rediss' for TLS)
// 一些其他配置
};

return {
stores: [
new Keyv({
store: new KeyvRedis(redisOptions),
namespace: 'logbook',
useKeyPrefix: false, // 如果想去掉重复的namespace的话,这里设置为false
}),

// 如果不想使用namespace的话,就和原来的一样
// new KeyvRedis(redisOptions),
],
};
},
inject: [ConfigService],
}),
],

})
export class AppModule {}


3. 使用


在模块(如common.service.ts)中使用,方法和原来一样,只是Cache类从@nestjs/cache-manager包中引入。

import { Cache, CACHE_MANAGER } from '@nestjs/cache-manager';
Injectable()
export class CommonService {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache ) {}

public async getCode(text: string) {
const captcha = svgCaptcha.create();
await this.cacheManager.set(
`test_key`,
text,
60 * 1000 * 10,
);
const val = await this.cacheManager.get<string>('test_key');
console.log(val)
}
}


参考:

> https://github.com/nestjs/cache-manager/pull/508
>
> https://keyv.org/docs/storage-adapters/redis/