~ mysql -uroot -p mysql> show variables like 'wait_timeout'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | wait_timeout | 28800 | +---------------+-------+ 1 row in set (0.00 sec) mysql> set global wait_timeout=10; Query OK, 0 rows affected (0.00 sec) mysql> show variables like 'wait_timeout'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | wait_timeout | 10 | +---------------+-------+ 1 row in set (0.00 sec)
修改文件:app-reconnection.js,在最后增加代码
~ vi app-reconnection.js
function query(){ console.log(new Date()); var sql = "show variables like 'wait_timeout'"; conn.query(sql, function (err, res) { console.log(res); }); } query(); setInterval(query, 15*1000);
程序会每融15秒,做一次查询。
控制台输出
D:\workspace\javascript\nodejs-node-mysql>node app-reconnect.js Wed Sep 11 2013 15:21:14 GMT+0800 (中国标准时间) [ { Variable_name: 'wait_timeout', Value: '10' } ] db error { [Error: Connection lost: The server closed the connection.] fatal: true, code: 'PROTOCOL_CONNECTION_LOST' } Wed Sep 11 2013 15:21:28 GMT+0800 (中国标准时间) [ { Variable_name: 'wait_timeout', Value: '10' } ] db error { [Error: Connection lost: The server closed the connection.] fatal: true, code: 'PROTOCOL_CONNECTION_LOST' } Wed Sep 11 2013 15:21:43 GMT+0800 (中国标准时间) [ { Variable_name: 'wait_timeout', Value: '10' } ]
我们自己的程序捕获了“PROTOCOL_CONNECTION_LOST”异常,并自动的实现了数据库重连。
4). MySQL连接池的超时测试
针对wait_timeout问题,我们再对连接做一下测试。
修改app-pooling.js文件
var mysql = require('mysql'); var pool = mysql.createPool({ host: 'localhost', user: 'nodejs', password: 'nodejs', database: 'nodejs', port: 3306 }); var selectSQL ="show variables like 'wait_timeout'"; pool.getConnection(function (err, conn) { if (err) console.log("POOL ==> " + err); function query(){ conn.query(selectSQL, function (err, res) { console.log(new Date()); console.log(res); conn.release(); }); } query(); setInterval(query, 5000); });
控制台输出:
D:\workspace\javascript\nodejs-node-mysql>node app-pooling.js Wed Sep 11 2013 15:32:25 GMT+0800 (中国标准时间) [ { Variable_name: 'wait_timeout', Value: '10' } ] Wed Sep 11 2013 15:32:30 GMT+0800 (中国标准时间) [ { Variable_name: 'wait_timeout', Value: '10' } ] Wed Sep 11 2013 15:32:35 GMT+0800 (中国标准时间) [ { Variable_name: 'wait_timeout', Value: '10' } ]
连接池,已经解决了自动重连的问题了,后面我们的开发,可以尽量使用pooling的方式。
您可能感兴趣的文章: