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

NestJS环境下按模式匹配批量获取Redis缓存键的问题咨询

功能实现说明

cache-manager 提供的 mget 方法不支持模式匹配,仅支持传入明确的缓存键数组批量查询,无法直接传入字符串模式匹配获取对应缓存。你无需更换其他Redis客户端,cache-manager-redis-store 底层默认封装了ioredis原生客户端,直接调用原生接口即可实现需求。

具体实现步骤
  • 第一步:注入Cache实例并获取原生Redis客户端
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';
import { Redis } from 'ioredis';

@Injectable()
export class CacheService {
  private redisClient: Redis;

  constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {
    // 从cache管理器中取出原生ioredis实例
    // 若你使用v3及以上版本的cache-manager-redis-store,可改为 this.cacheManager.store.client 获取
    this.redisClient = this.cacheManager.store.getClient();
  }
}
  • 第二步:封装模式匹配批量查询方法
    优先使用SCAN命令遍历匹配键,避免使用KEYS命令导致Redis主线程阻塞:
async getCachesByPattern(pattern: string) {
  const matchedKeys: string[] = [];
  let cursor = '0';

  // 迭代遍历所有键匹配模式
  do {
    const [newCursor, keys] = await this.redisClient.scan(
      cursor,
      'MATCH',
      pattern,
      'COUNT',
      100 // 单次遍历拉取的键数量,可根据业务场景调整
    );
    cursor = newCursor;
    matchedKeys.push(...keys);
  } while (cursor !== '0');

  if (matchedKeys.length === 0) return [];
  // 调用mget批量获取所有匹配键的缓存值
  return this.cacheManager.mget(...matchedKeys);
}
注意事项
  • Redis模式匹配规则和原生语法一致:比如匹配所有包含test字符串的键,传入*test*即可;匹配前缀为user:的键传入user:*
  • 生产环境禁止使用KEYS命令做全量匹配,数据量大时会长时间阻塞Redis主线程,引发服务故障

内容的提问来源于stack exchange,提问作者Anesh P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:54:03