js mysql isconnected,通过单例的node.js mySQL连接

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值