node.js mySQL connection via a singleton

北战南征 提交于 2019-12-02 05:06:56

问题


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 setting for this connection held by the singleton.

This connection is supposed to live throughout the life cycle of the app. I searched and found some persistence examples using pool but not sure if this applies to this example, there's no pool of connections, there's only one connection to be shared between the components, the question is, is there some timeout setting that will kill the connection after it's held for long?

puremvc.define(
{
name: "common.model.connections.App",

constructor: function() { 
    var mysql = require("mysql");
    this.connection = mysql.createConnection({
        host: common.Config.mySQLHost,
        user: common.Config.mySQLUsername,
        password: common.Config.mySQLPassword,
        database: common.Config.mySQLDatabase
    });

    this.connection.connect();
 }
    },
{
}, 
{
NAME: "App",
instance: null,
connection: null,

getInstance: function() {
    if(common.model.connections.App.instance == null) {
        common.model.connections.App.instance = new common.model.connections.Fico();
    }
    return common.model.connections.App.instance;
},

getConnection: function() {
    return common.model.connections.App.getInstance().connection;
}
}
);

回答1:


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;
}


来源:https://stackoverflow.com/questions/26533936/node-js-mysql-connection-via-a-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!