繁体   English   中英

为什么Node.js中的MySQL如此之慢?

[英]Why is MySQL in Node.js so slow?

我的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个连接吗?

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

这个链接谈到' node-mysql-pool ',它是node.js的MySQL连接池

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

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

它第一次花费一些时间来建立连接。 希望这有助于〜

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM