node-mysql连接池

Ome*_*lam 14 mysql database connection-pooling node.js

我正在使用node-mysql模块(https://github.com/felixge/node-mysql)或(http://utahjs.com/2010/09/22/nodejs-and-mysql-introduction/).

此API处理连接池也是如此?

我的意思是每个用户请求我打电话Client.connect()来查询MySQL并释放连接:Client.end().

这是正确的方法,还是我应该只在代码中连接/断开一次.

我正在从这份文件中学习:https://github.com/felixge/node-mysql/blob/master/Readme.md

And*_*rov 20

更新:2013年2月 - 池节点已添加到node-mysql,请参阅docs

使用内置池的示例:

var pool = require('mysql').createPool(opts);

pool.getConnection(function(err, conn) {
  conn.query('select 1+1', function(err, res) {
    conn.release();
  });
});
Run Code Online (Sandbox Code Playgroud)

2013年前解决方案:

您可以使用node-poolmysql-pool或使用自己的简单循环池

function Pool(num_conns)
{
    this.pool = [];
    for(var i=0; i < num_conns; ++i)
        this.pool.push(createConnection()); // your new Client + auth
    this.last = 0;
}

Pool.prototype.get = function()
{
    var cli = this.pool[this.last];
    this.last++;
    if (this.last == this.pool.length) // cyclic increment
       this.last = 0;
    return cli;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以希望让所有查询回调在1秒内执行:

var p = new Pool(16);
for (var i=0; i < 10; ++i)
{
    p.get().query('select sleep(1)', function() { console.log('ready'); } ); // server blocks for 1 second
}
Run Code Online (Sandbox Code Playgroud)


VCD*_*VCD 5

node-mysql模块现在支持连接池.

参考:https://github.com/felixge/node-mysql#pooling-connections