【问题标题】:Why is MySQL in Node.js so slow?为什么 Node.js 中的 MySQL 这么慢?
【发布时间】:2012-11-13 18:55:28
【问题描述】:

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

【问题讨论】:

  • 查询是什么?它有适当的索引支持吗?
  • 你需要发布更多的伪代码来获得帮助。
  • 在命令行而不是通过节点运行查询需要多长时间?
  • 感谢大家的帮助。 20 秒后,我运行了一个有 100 个并发请求的查询。我除了它将需要 10 秒。但实际上需要20s。我不知道为什么?我已经将最大连接数设置为10,它将有10个mysql连接备用,QPS必须是10。谁能告诉我为什么?
  • 如何创建这 100 个请求?如果它有 100 个浏览器标签,那么每个会触发 2 个请求(url + favicon)

标签: mysql node.js node-mysql


【解决方案1】:

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

link 谈到,'node-mysql-pool' 这是一个用于 node.js 的 MySQL 连接池

【讨论】:

  • 使用node-mysqlcreatePool({})函数创建连接池可能会更好
【解决方案2】:

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

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

第一次花费一些时间建立连接。希望对你有帮助~

【讨论】:

    猜你喜欢
    • 2012-08-10
    • 2019-06-28
    • 2012-10-17
    • 2012-11-19
    • 1970-01-01
    • 2016-10-24
    • 2010-10-26
    • 2011-03-07
    • 2013-03-18
    相关资源
    最近更新 更多