You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJs中Redis缓存管理器set方法TTL参数类型错误求助

解决NestJs Redis缓存set方法类型错误及缓存立即失效问题

问题原因

你遇到的问题是@nestjs/cache-manager或底层cache-manager库版本升级导致的API变更:

  • 旧版本允许通过{ ttl: 60 }对象格式传入过期时间(单位为秒)
  • 新版本要求第三个参数直接传数字(单位改为毫秒),或传入含ttl的对象但单位为毫秒,类型校验也随之严格,导致原代码抛出类型错误
  • 直接传60时缓存立即被移除,是因为新版本中ttl单位变为毫秒,60毫秒的过期时间会让缓存瞬间失效

解决方案

方案1:适配新版本API(推荐)

将过期时间转换为毫秒后传入,两种写法可选:

// 方式1:直接传毫秒数(对应60秒)
await this.productCacheManager.set('products/time', data, 60 * 1000);

// 方式2:使用对象格式(同样指定毫秒级ttl)
await this.productCacheManager.set('products/time', data, { ttl: 60 * 1000 });

方案2:降级回兼容版本

如果想继续使用原代码的参数格式,可以降级到旧版本依赖:

# 安装兼容版本的依赖包
npm install @nestjs/cache-manager@0.6.0 cache-manager@4.1.0 cache-manager-redis-store@2.0.0

方案3:全局配置默认TTL

在CacheModule注册时设置全局默认过期时间,避免每次调用set都手动传参:

import { CacheModule } from '@nestjs/cache-manager';
import * as redisStore from 'cache-manager-redis-store';

@Module({
  imports: [
    CacheModule.register({
      store: redisStore,
      host: 'localhost', // 你的Redis服务地址
      port: 6379, // 你的Redis服务端口
      ttl: 60 * 1000, // 全局默认60秒过期(毫秒单位)
    }),
  ],
})
export class AppModule {}

此时调用set可省略ttl参数,直接使用全局配置:

await this.productCacheManager.set('products/time', data);

内容的提问来源于stack exchange,提问作者Tayber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:20:29