通过单例的node.js mySQL连接 [英] node.js mySQL connection via a singleton
问题描述
我在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;
}
}
);
推荐答案
这实际上是MySQL问题,而不是Node.js.您可以使用MySQL的属性wait_timeout
来增加保持连接打开的时间.
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.
在此处
以下是您的单例的代码示例,当当前的单例关闭时,它将创建一个新的连接.在这种情况下,如果您始终使用App Singleton获取连接,则永远不会有超过1个活动的连接:
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;
}
这篇关于通过单例的node.js mySQL连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!