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

Nest.js Cache Manager从Redis获取值返回Undefined问题求助

Nest.js Cache Manager 操作Redis时get返回Undefined问题排查与解决

可能的原因及排查步骤

1. Redis连接与配置错误

确保你的Nest应用正确配置了Redis作为Cache Store:

// app.module.ts
import { Module, CacheModule } from '@nestjs/common';
// 注意:若使用最新版cache-manager,可能需要安装cache-manager-redis-yet替代redis-store
import * as redisStore from 'cache-manager-redis-store';

@Module({
  imports: [
    CacheModule.register({
      isGlobal: true, // 可选,全局注册缓存模块
      store: redisStore,
      host: 'localhost',
      port: 6379,
      // 若Redis有密码或其他配置,补充对应字段
      // password: 'your-redis-password',
      // db: 0,
    }),
  ],
})
export class AppModule {}
  • 验证Redis服务是否运行:执行redis-cli ping,返回PONG说明服务正常
  • 检查配置的主机、端口、密码是否与Redis实例一致

2. 缓存键类型不匹配

Redis的键均为字符串类型,若你的id是数字类型,存入和读取时需统一转为字符串,否则会出现键不匹配的情况:

// 统一将id转为字符串作为缓存键
const cacheKey = String(id);
const cacheData = await this.cacheStore.get<number>(cacheKey);

3. 数据序列化/反序列化异常

你的代码中使用plainToClass(Number, cacheData)是错误的:

  • plainToClass用于将普通对象转换为类实例,转换Number类会生成Number实例对象,存入Redis时会被序列化为非预期格式(如{}),导致读取时无法解析为有效数字
  • 直接使用Number()或类型断言转换数值即可

4. 代码逻辑冗余与错误

你的代码存在不必要的await和逻辑冗余:

  • await { childrenCount: tk }完全无效,对象不是Promise,无需await
  • cacheStore.set的返回值通常是OK(Redis协议响应),而非存入的数值,不能直接作为返回值

修正后的代码示例

import { Inject, Injectable } from '@nestjs/common';
import { CacheStore } from '@nestjs/common/cache';
import { isNil } from '@nestjs/common/utils/shared.utils';

@Injectable()
export class ChildCountService {
  constructor(
    @Inject(CACHE_MANAGER) private readonly cacheStore: CacheStore,
    private readonly service: YourBusinessService, // 替换为你的业务服务
  ) {}

  async getChildrenCount(id: string | number) {
    const cacheKey = String(id);
    const cacheData = await this.cacheStore.get<number>(cacheKey);

    if (!isNil(cacheData)) {
      return { childrenCount: cacheData };
    }

    // 缓存未命中,从业务服务获取数据
    const response = await this.service.findChildrenCountById(id);
    const resolvedCount = Number(response); // 确保转换为数字类型

    // 存入缓存
    await this.cacheStore.set(cacheKey, resolvedCount, { ttl: 24 * 60 * 60 });

    return { childrenCount: resolvedCount };
  }
}

额外调试技巧

  • 使用redis-cli keys *查看Redis中所有键,确认目标键是否存在
  • 执行redis-cli get <cacheKey>查看键对应的实际值,验证是否是预期的数字
  • 在代码中添加日志,打印cacheKey、cacheData、resolvedCount等关键变量,定位问题点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:30:43