node.js mySQL connection via a singleton

后端 未结 1 789
梦毁少年i
梦毁少年i 2021-01-22 09:59

I\'m using a singleton pattern for mySQL connections in node.js, there\'s one and only one connection for the whole application to use, my concern is if there\'s some timeout s

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 10:39

    This is actually a MySQL concern and not Node.js. You can use the property wait_timeout of the MySQL to increase the number of time to keep the connection opened.

    Check more details about this property here

    Below is a code example for your singleton that will create a new connection when the current one is closed. In the scenario, you will never have more than 1 connection active if you always use the App Singleton to get the connection:

    getConnection: function() {
        var app = common.model.connections.App.getInstance();
        if(!app.connection.isConnected()){
           //connect if connection is closed.
           app.connection.connect();
        }
        return app.connection;
    }
    

    0 讨论(0)
提交回复
热议问题