简体   繁体   中英

node.js mySQL connection via a singleton

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM