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

使用NestJS CacheModule设置Redis键TTL异常,始终显示5000s求助

问题:NestJS cacheManager.set 设置TTL不生效,Redis始终显示5000秒

问题详情

使用Redis作为缓存,GUI工具为Redis-commander。调用NestJS的cacheManager.set方法尝试设置不同TTL值(1秒、10秒、200秒、2000秒),但Redis-commander中该键的TTL始终显示为5000秒。

相关代码

设置缓存键的代码:

await this.cacheManager.set(keyRfToken, refreshToken, 2000)

CacheModule配置代码:

const redisStore = require('cache-manager-redis-store').redisStore
import { CacheModule } from '@nestjs/cache-manager';
@Module({
  imports: [
    CacheModule.register({
      isGlobal : true,
      store : redisStore,
      host : "localhost",
      port : 6379,
    }),
    // 其他模块...
  ],
  // 其他配置...
})

Redis-commander界面截图

Redis-commander中显示的TTL为5000秒


解决方案

1. 修正cacheManager.set的参数格式

当前主流版本的cache-manager(配合@nestjs/cache-manager)要求,设置TTL时需要将其放在配置对象中,而非直接传递数字。旧写法会被忽略,转而使用Redis store的默认TTL(恰好为5000秒)。

修改后的代码:

// 正确写法:将TTL放入options对象的ttl属性中
await this.cacheManager.set(keyRfToken, refreshToken, { ttl: 2000 });

2. 验证版本兼容性

确保依赖版本匹配:

  • @nestjs/cache-manager v2.x 对应 cache-manager v5.x+
  • cache-manager-redis-store v3.x+ 必须使用上述对象式的TTL传参方式

可查看package.json中的依赖版本,若版本不匹配,建议升级到兼容版本。

3. 清除旧缓存键并重新测试

Redis中已存在的旧键不会自动更新TTL,需先通过Redis-commander或命令行删除对应键,再重新执行设置代码验证效果。

补充说明

若需要设置全局默认TTL,可以在CacheModule.register中添加defaultTTL配置:

CacheModule.register({
  isGlobal : true,
  store : redisStore,
  host : "localhost",
  port : 6379,
  defaultTTL: 3600, // 全局默认TTL,单位秒
}),

单独设置键的TTL时,传入的{ ttl: xxx }会覆盖全局默认值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:05:11