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

node-redis执行任意操作触发Socket意外关闭且无法正常重连问题

解决Node-Redis 4.5.1 SocketClosedUnexpectedlyError导致应用崩溃问题

核心问题分析

你的代码虽监听了error事件,但执行hGetAll等命令时抛出的SocketClosedUnexpectedlyError未被捕获,直接导致进程崩溃。同时需排查连接配置、Redis服务器端设置是否存在异常。

具体修复步骤

1. 捕获命令执行时的异常

所有异步Redis命令操作必须用try/catch包裹,避免未捕获的Promise rejection导致进程崩溃:

async function testRedis() {
    let client = createClient({
        url: 'redis://localhost:8081'
    });
    client.on("error", (err) => console.error("client err====:", err));
    client.on('connect', () => console.log('client is connect'));
    client.on('reconnecting', () => console.log('client is reconnecting'));
    client.on('ready', () => console.log('client is ready'));

    try {
        await client.connect();
        let kek = await client.hGetAll('Caas.ExposeServerCache:IE:DB:G001');
        console.log("KEK::: ", kek); // 避免用+拼接对象,改用逗号输出完整内容
    } catch (err) {
        console.error("Command execution err:", err);
        // 可在此添加重试逻辑或其他降级处理
    } finally {
        // 按需关闭连接,长期运行的服务可保持长连接
        // await client.disconnect();
    }
}

2. 验证连接配置正确性

  • 确认Redis CLI连接的端口确实为8081(Redis默认端口是6379),执行redis-cli -p 8081测试,避免代码端口配置错误。
  • 若Redis设置了认证,需在createClient中添加用户名密码:
createClient({
    url: 'redis://localhost:8081',
    password: 'your-redis-password'
});

3. 调整Redis服务器端配置

检查Redis配置文件(redis.conf)中的关键参数:

  • tcp-keepalive:保持默认300,确保TCP连接活跃,避免服务器主动关闭闲置连接。
  • timeout:设为0禁用自动闲置连接关闭,若当前为非0值会触发主动断连。
  • 修改后重启Redis服务使配置生效。

4. 升级node-redis版本

node-redis 4.5.1存在已知的连接稳定性问题,升级到最新稳定版可修复部分bug:

npm install redis@latest

额外提示

  • 避免在测试代码中重复创建客户端实例,建议全局复用一个连接,减少频繁创建销毁连接带来的异常。
  • 若使用测试框架(如Mocha/Jest),需确保测试结束后正确关闭Redis客户端,避免残留连接导致后续异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:01:22