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

Node.js中Redis v4按模式获取Keys失效,消息无法发布求助

问题解决:Redis 4版本下keys命令回调失效的修复

核心原因

Redis 4.x版本的Node.js客户端(如node-redis v4)完全废弃了回调风格的API,所有命令默认返回Promise。你原来的代码用回调调用keys,但这个回调函数根本不会被执行,导致后续的日志和消息分发逻辑全部没触发。

修改方案

将回调写法改为async/await(或Promise的.then())风格,适配Redis 4的API:

async myFunction(someData){
  console.log(someData) // 正常输出
  try {
    // 用await获取keys结果,替代回调
    const ids = await this.redisClient.keys('REDIS_SUBSCRIBER_SOCKET_CHANNEL_*');
    console.log('ids: ' + ids);
    ids.forEach(id => {
      console.log(
        'Distributing: ' + JSON.stringify(someData),
      );
      this.publisherClient.publish(id, JSON.stringify(someData));
    });
  } catch (err) {
    // 捕获并打印错误
    console.log(err);
  }
}

生产环境优化建议

keys命令在Redis数据量大时会阻塞服务,建议改用scan命令迭代获取匹配的Key,避免性能问题:

// 封装scan获取匹配Key的函数
async getPatternKeys(pattern) {
  let cursor = 0;
  const matchedKeys = [];
  do {
    const { cursor: nextCursor, keys } = await this.redisClient.scan(cursor, { MATCH: pattern });
    cursor = nextCursor;
    matchedKeys.push(...keys);
  } while (cursor !== 0);
  return matchedKeys;
}

// 在myFunction中调用
async myFunction(someData){
  console.log(someData)
  try {
    const ids = await this.getPatternKeys('REDIS_SUBSCRIBER_SOCKET_CHANNEL_*');
    console.log('ids: ' + ids);
    ids.forEach(id => {
      console.log(
        'Distributing: ' + JSON.stringify(someData),
      );
      this.publisherClient.publish(id, JSON.stringify(someData));
    });
  } catch (err) {
    console.log(err);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:42:38