8

我的 Node.js 代码如下

CODE1:下面

var http=require('http');
var MySQL = require('mysql');

mysql = MySQL.createConnection(...)

http.createServer(function(req, res){
    // the query will take several seconds
    mysql.query("SELECT SLEEP(1)", function....)
});
http.listen(...);

问题是当我刷新页面太快时服务器会崩溃。我认为是 node-mysql 模块的问题,它处理队列中的查询。所以我尝试创建一个连接池。

CODE2: 下面

....
var pool = require('generic-pool');
var mp   = pool.Pool({
    ...
    create: function(cb){
        client = MySQL.createConnection(...);
        cb(null, client)
    },
    max: 10, // up to 10 connection
    min: 2,
    ...
});
....
    mp.acquire(function(err, mysql){

        // the query will take several seconds
        mysql.query("SELECT SLEEP(1)", function....)
        mp.release(mysql);
    });
....

但问题依然存在,为什么呢?我怎样才能解决这个问题。

编辑:我以 100 个并发启动 100 个请求,预计需要 10 秒。但这需要20秒。为什么?池是否只支持最多 5 个连接?

4

2 回答 2

1

连接池是处理多个并发请求的好方法。但是,我们为什么不能使用 mysql-specific 池而不是使用“通用资源池”呢?

链接讨论“ node-mysql-pool ”,它是 node.js 的 MySQL 连接池

于 2012-12-24T05:11:32.070 回答
1

免责声明:我编写模块来解决此类问题。

npm install mysql-simple-pool

现在您可以配置连接池。我最多使用 100 个连接。

var Pool = require('mysql-simple-pool');
var pool = new Pool(100, {
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'test'
});

现在您可以编写一个测试函数来对其进行测试。

function test() {
    var counter = 0;
    var start = new Date().getTime();
    for (var xa = 0; xa < 10; xa++) {
        pool.query('SELECT SLEEP(1)', function(err, results) {
            counter++;
            if (counter == 10) {
                var end = new Date().getTime();
                console.log('Time spend is ' + (end - start) + 'ms');
                test();
            }
        });
    }
}
test();

这是输出......

Time spend is 1044ms
Time spend is 1006ms
Time spend is 1005ms
Time spend is 1006ms
Time spend is 1007ms
Time spend is 1005ms
Time spend is 1005ms
Time spend is 1004ms
Time spend is 1005ms
Time spend is 1005ms

第一次花费一些时间建立连接。希望这会有所帮助~

于 2013-01-07T22:16:53.743 回答