我已经在 nestjs 中将 redis 注册为缓存管理器,它从 0 的环境中获取默认值,即某些键不需要限制。但是我想使用 set(key, value, ttl) 将自定义 ttl 传递给另一个键,它仍然从 env 而不是 set 函数中获取 ttl。
redis 模块
@Module({
imports: [
CacheModule.registerAsync({
imports: [],
useFactory: async (
config: ConfigType<typeof configuration>,
): RedisClientOptions => ({
store: redisStore,
socket: {
host: config.redis.host,
port: config.redis.port,
tls: config.redis.tls,
},
ttl: parseInt(config.redis.ttl, 10),
}),
inject: [configuration.KEY],
}),
],
providers: [RedisService],
exports: [RedisService],
})
export class RedisModule {}
redis 服务
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';
@Injectable()
export class RedisService {
constructor(@Inject(CACHE_MANAGER) private cache: Cache) {}
async setWithTtl(
key: string | number,
value: any,
): Promise<void> {
try {
await this.cache.set(
JSON.stringify(key),
JSON.stringify(value),
500,
);
return;
} catch (err) {
throw err;
}
}
我不确定,但也许你正面临这种情况?
警告 缓存管理器版本 4 使用秒作为 TTL(生存时间)。当前版本的缓存管理器 (v5) 已改为使用毫秒。 NestJS 不转换值,只是将您提供的 ttl 转发给库。换句话说: 如果使用缓存管理器 v4,则在几秒钟内提供 ttl 如果使用缓存管理器 v5,以毫秒为单位提供 ttl 文档指的是秒,因为 NestJS 是针对缓存管理器版本 4 发布的。
更新set函数为
await this.cache.set(
JSON.stringify(key),
JSON.stringify(value),
{ ttl: 500 } as any,
);
这里 500 必须以秒为单位而不是以毫秒为单位,即使缓存管理器是 v5
有关该问题的更多详细信息,请参见此处