node mysql连接出现Error: Connection lost The server closed the connection,原因是mysql连接建立后有一个保活时间,这个wait_time实测大概是在大几个小时左右,时间超过mysql就会自动关闭连接,所以方法就是检测到出现Error: Connection lost The server closed the connection时自动重连就行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 let connection ='' ;mysql = require ('mysql' ); function handleDisconnection ( ) { connection = mysql.createConnection ({ host : 'localhost' , user : 'root' , password : '' , database : '' , port : '3306' }) connection.connect (function (err ) { if (err) { setTimeout ('handleDisconnection()' , 2000 ); } }); connection.on ('error' , function (err ) { logger.error ('db error' , err); if (err.code === 'PROTOCOL_CONNECTION_LOST' ) { logger.error ('db error执行重连:' + err.message ); handleDisconnection (); } else { throw err; } }); } handleDisconnection ();
这里声明一个全局变量connection,然后在handleDisconnection()里创建连接赋给connection,就可以在下面使用了 例如:
1 2 3 4 5 function getList (callback ) { connection.query ('select * from xxx' , (err, data, fields ) => { return callback (err, data, fields) }) }
下面是截图修改后的效果