node-mysql连接池 [英] node-mysql connection pooling
问题描述
我使用的是node-mysql模组( https://github.com/felixge/node-mysql )OR( http://utahjs.com/2010/ 09/22 / nodejs-and-mysql-introduction / )。
I am using node-mysql module (https://github.com/felixge/node-mysql) OR (http://utahjs.com/2010/09/22/nodejs-and-mysql-introduction/) .
这个API处理连接池吗?
Is this API handling connection pooling as well?
我的意思是每个用户请求我调用 Client.connect()
查询MySQL并释放连接: Client.end()
。
I mean with every user request I am calling Client.connect()
to query the MySQL and to release the connection: Client.end()
.
这是正确的方法,或者我应该在代码中只连接/断开一次。
Is this the right way, or should I connect/disconnect only once in a code.
https://github.com/felixge/node-mysql/blob/master /Readme.md
推荐答案
更新:2013年2月 - 池支持已添加到node-mysql, a href =https://github.com/felixge/node-mysql#pooling-connections =noreferrer> docs
Update: Feb 2013 - pool support has been added to node-mysql, see docs
使用示例内置池:
var pool = require('mysql').createPool(opts);
pool.getConnection(function(err, conn) {
conn.query('select 1+1', function(err, res) {
conn.release();
});
});
2013年前解决方案:
Pre 2013 solutions:
请使用节点池或 mysql-pool 或使用您自己的简单循环池
You can use node-pool or mysql-pool or use your own simple round-robin 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;
}
现在你可以希望所有的查询回调在1秒内执行: / p>
now you can hope to have all queries callbacks to execute in 1 second:
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
}
这篇关于node-mysql连接池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!