NestJS Cache Manager调用Redis SET命令始终返回true问题
NestJS cache-manager Redis set指令返回值异常问题
问题背景
使用cache-manager@3.6.0和cache-manager-redis-store@2.0.0时,调用底层Redis客户端的set方法并传入NX参数,返回值isSet始终为true;但在Redis CLI中重复执行set key val ex ttl nx,键存在时会返回nil,不存在时返回OK。
问题原因
你当前使用的cache-manager-redis-store@2.0.0依赖node_redis v3.x,该版本的Redis客户端set方法参数格式与Redis CLI不兼容:
- Redis CLI采用位置参数直接传递命令选项(如
EX、NX) - 但node_redis v3要求通过选项对象来指定过期时间和存在性判断条件,而非直接传递命令参数。
你的写法set(key, value, 'EX', ttl, 'NX')会被node_redis v3解析错误,导致NX选项完全不生效——Redis每次都会执行set操作并返回OK,而cache-manager-redis-store会将OK隐式转换为true,因此isSet始终为true。
解决方法
改用node_redis v3支持的选项对象格式调用set,并直接判断原生返回值:
const result = await this.cacheManager.store.getClient().set(key, value, { EX: ttl, // 设置过期时间(单位:秒) NX: true // 仅当key不存在时执行set操作 }); // 原生返回值:成功返回'OK',失败(key已存在)返回null const isSet = result === 'OK'; console.log("isSet => " + isSet); if (isSet) { try { // 执行你的业务逻辑 } catch(err) { console.log("err => " + err); throw err; } finally { // await this.cacheManager.del(key); } }
版本升级说明
如果后续升级到cache-manager-redis-store@5.x+(依赖node_redis v4.x),需使用该版本支持的新写法:
// 写法1:选项对象 const result = await this.cacheManager.store.getClient().Set(key, value, { EX: ttl, NX: true }); // 写法2:链式调用 const result = await this.cacheManager.store.getClient().set(key, value).EX(ttl).NX();
内容的提问来源于stack exchange,提问作者dexdagr8
相关产品推荐
相关产品推荐

