You need to enable JavaScript to run this app. 如何通过cache-manager检索内存缓存中存储的所有数据?
优惠活动
大模型
产品
解决方案
定价
更多

如何通过cache-manager检索内存缓存中存储的所有数据?

基于cache-manager内存存储的全量缓存检索实现方案

默认搭配NestJS使用的内存版cache-manager没有内置现成的getAll()全量拉取方法,可通过以下两种可落地方案实现类似的全量缓存检索能力:

方案1:调用底层存储的原生键遍历能力

  • 内存版cache-manager的底层实现封装了统一的键遍历接口,不需要额外安装依赖即可直接使用
  • 实现逻辑:先通过底层存储实例拿到所有未过期的有效键,再批量拉取每个键对应的缓存值
  • 示例代码:
import { CACHE_MANAGER, Cache, Inject, Injectable } from '@nestjs/common';

@Injectable()
export class CacheAccessorService {
  constructor(
    @Inject(CACHE_MANAGER) private readonly cacheManager: Cache
  ) {}

  /**
   * 拉取当前所有有效缓存的键值对
   */
  async retrieveAllCacheEntries() {
    // 获取底层存储的所有有效键
    const activeCacheKeys = await this.cacheManager.store.keys();
    // 批量读取每个键对应的缓存值
    const cacheEntries = await Promise.all(
      activeCacheKeys.map(async (key) => ({
        cacheKey: key,
        cacheValue: await this.cacheManager.get(key)
      }))
    );
    return cacheEntries;
  }
}
  • 兼容说明:这套逻辑兼容cache-manager v4及以上版本,不仅适用于内存存储,后续如果切换到Redis、文件型等其他cache-manager适配的存储引擎,只要存储适配器实现了统一的keys()接口,代码不需要修改即可运行。

方案2:自定义键映射层解耦底层实现依赖

  • 适合对版本稳定性要求高的场景,避免因cache-manager内部结构变动导致功能失效
  • 实现逻辑:在所有写入缓存的流程中,同步把写入的键维护到一个固定的全局缓存键集合中;拉取全量数据时,直接遍历这个集合读取对应值
  • 示例代码:
// 固定专属键,用于存储全量缓存键的集合
const ALL_CACHE_KEYS_REF = '__internal_all_cache_keys__';

/**
 * 重写缓存写入逻辑,同步维护键集合
 */
async writeCache(key: string, value: unknown, ttl?: number) {
  await this.cacheManager.set(key, value, ttl);
  // 读取现有键集合,追加新写入的键
  const existingKeys = (await this.cacheManager.get<string[]>(ALL_CACHE_KEYS_REF)) || [];
  if (!existingKeys.includes(key)) {
    existingKeys.push(key);
    await this.cacheManager.set(ALL_CACHE_KEYS_REF, existingKeys);
  }
}

/**
 * 拉取全量缓存数据
 */
async retrieveAllCacheEntries() {
  const trackedKeys = (await this.cacheManager.get<string[]>(ALL_CACHE_KEYS_REF)) || [];
  return Promise.all(
    trackedKeys.map(async (key) => ({
      cacheKey: key,
      cacheValue: await this.cacheManager.get(key)
    }))
  );
}

注意:如果缓存配置了TTL自动过期机制,两种方案获取的都是当前时刻尚未过期的有效缓存条目,已经被自动清理的过期缓存不会出现在返回结果中,无需额外做过期状态判断。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.11 12:36:09