【问题标题】:Reusing Redis Connection: Socket Closed Unexpectedly - node-redis重用 Redis 连接:套接字意外关闭 - node-redis
【发布时间】:2022-06-16 15:49:29
【问题描述】:

首先,让我告诉你我是如何在我的 NodeJS 应用程序中使用 Redis 连接的:

  • 我正在使用单例类在整个应用程序中重复使用一个连接。
class RDB {

    static async getClient() {
        if (this.client) {
            return this.client
        }

        let startTime = Date.now();

        this.client = createClient({
            url: config.redis.uri
        });

        await this.client.connect();

        return this.client;
    }

}

出于某种原因 - 我不知道 - 我的应用程序有时会无缘无故地崩溃并给出错误 - 这种情况大约每周发生一次或两次:

Error: Socket closed unexpectedly

现在,我的问题:

  1. 这样使用 Redis 连接好吗?我的方法有问题吗?
  2. 为什么会发生这种情况?为什么我的套接字会意外关闭?
  3. 有没有办法捕获这个错误(使用我的方法)或任何其他实现 Redis 连接的良好做法?

【问题讨论】:

    标签: node.js sockets redis node-redis


    【解决方案1】:

    您应该声明一个 RDB 类的私有静态成员“client”,如下所示:

    private static client;
    

    在静态方法中,你不能引用'this'的实例,你需要像这样引用静态类成员:

    RDB.client
    

    最好检查客户端的连接是否打开,而不是简单地检查客户端是否存在(考虑到您正在使用“redis”npm 库)。像这样:

    if (RDB.client && RDB.client.isOpen) 
    

    更改后,您的代码应如下所示:

    class RDB {
        private static client;
    
        static async getClient() {
            if (RDB.client && RDB.client.isOpen) {
                return RDB.client;
            }
    
            RDB.client = createClient({
                url: config.redis.uri
            });
    
            await RDB.client.connect();
    
            return RDB.client;
        }
    }
    

    注意:connect()方法和isOpen属性只存在于redis版本^4.0.0中。

    另外,我不明白 startTime 变量的用途是什么,但您可能会在实际代码中使用它,而不是在这个 sn-p 中。如果这有帮助,请告诉我!

    【讨论】:

      【解决方案2】:

      我意外地遇到了类似的套接字关闭问题。当我将 node-redis 从 3.x 升级到 4.x 时,问题就开始了。在我将我的 redis-server 从 5.x 升级到 6.x 后,这个问题就消失了。

      【讨论】:

        【解决方案3】:

        我使用“错误”侦听器解决了这个问题。只听它 - 避免节点应用程序崩溃。

        client.on("error", function(error) {
           console.error(error);
           // I report it onto a logging service like Sentry. 
        });
        

        【讨论】:

          猜你喜欢
          • 2022-11-26
          • 2022-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-06
          • 2012-04-14
          • 2017-06-12
          • 2012-12-19
          相关资源
          最近更新 更多