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

我的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模块的问题,它处理队列中的查询。所以我尝试创build一个连接池。

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

连接池是处理多个并发请求的很好的解决scheme。 但是,不使用“通用资源池”,为什么我们不能使用特定于MySQL的池呢?

这个链接讲的是node.js的一个MySQL连接池“ node-mysql-pool

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

 npm install mysql-simple-pool 

现在你可以configuration你的连接池了。 我使用最多100个连接。

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

现在你可以编写一个testing函数来完成testing。

 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 

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