与NodeJS的MySQL连接错误

时间:2017-02-24 11:32:49

标签: javascript mysql node.js server centos

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var mysql = require('mysql');

app.get('/', function(req, res){
  res.send('<h1>My App</h1>');
});

var db_config = {
  host: 'localhost',
  user: 'root',
  database: 'database',
  password: '',
  dialect: 'mysql',
  insecureAuth: true
};

var connection;

function handleDisconnect() {
  connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                  // the old one cannot be reused.
  connection.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      handleDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}
handleDisconnect();

http.listen(3000, function(){
  console.log('listening on *:3000');
});

.............

我正在开发一个应用程序,它可以从数据库返回实时得分更新,如上面的代码所示。当我用localhost(wamp)执行上面的程序时,它运行正常。使用带有MariaDB的CentOS 7执行时,它会返回错误说明:

db error { Error: Connection lost: The server closed the connection.

我已按照此thread对我的代码进行了一些更改。 但它没有用。而且我也尝试使用Pooling。帮我解决这个问题。

0 个答案:

没有答案