node.js mysql的Connection lost The server closed the connection问题

一、问题(错误日志)

Sep 27 11:22:29 ubuntu node[66931]: events.js:183
Sep 27 11:22:29 ubuntu node[66931]:       throw er; // Unhandled 'error' event
Sep 27 11:22:29 ubuntu node[66931]:       ^
Sep 27 11:22:29 ubuntu node[66931]: Error: Connection lost: The server closed the connection.
Sep 27 11:22:29 ubuntu node[66931]:     at Protocol.end (/home/yiyun/szwapi/src/node_modules/mysql/lib/protocol/Protocol.js:112:13)
Sep 27 11:22:29 ubuntu node[66931]:     at Socket. (/home/yiyun/szwapi/src/node_modules/mysql/lib/Connection.js:97:28)
Sep 27 11:22:29 ubuntu node[66931]:     at Socket. (/home/yiyun/szwapi/src/node_modules/mysql/lib/Connection.js:502:10)
Sep 27 11:22:29 ubuntu node[66931]:     at emitNone (events.js:111:20)
Sep 27 11:22:29 ubuntu node[66931]:     at Socket.emit (events.js:208:7)
Sep 27 11:22:29 ubuntu node[66931]:     at endReadableNT (_stream_readable.js:1064:12)
Sep 27 11:22:29 ubuntu node[66931]:     at _combinedTickCallback (internal/process/next_tick.js:138:11)
Sep 27 11:22:29 ubuntu node[66931]:     at process._tickCallback (internal/process/next_tick.js:180:9)
Sep 27 11:22:29 ubuntu systemd[1]: szwapi.service: Main process exited, code=exited, status=1/FAILURE
Sep 27 11:22:29 ubuntu systemd[1]: szwapi.service: Unit entered failed state.
Sep 27 11:22:29 ubuntu systemd[1]: szwapi.service: Failed with result 'exit-code'.
Sep 27 11:22:29 ubuntu systemd[1]: szwapi.service: Service hold-off time over, scheduling restart.

MySQL有一个wait_time当超过这个时间的时候连接会丢失,再去请求MySQL的时候会连接不上MySQL服务。

二、解决方法(使用连接池),接封装成module,取名为‘sqlPool.js’代码如下:

var mysql  = require('mysql');

var pool = mysql.createPool({
    host: "127.0.0.1",
    user: "root",
    password: "123",
    database: "test",
    ssl: false,
    dateStrings: true
});

var query = function(sql,callback){
    pool.getConnection(function(err,conn){
        if(err){
            callback(err,null);
        }else{
            conn.query(sql,function(err,results){
                callback(err,results);
            });
            conn.release();
        }
    });
};

module.exports = query;

使用JS模块,代码如下:

var query=require("./sqlPool.js");

query("select 1 from 1",function(err,fields){
    //do something
});

 

你可能感兴趣的:(node.js,mysql)