0

我是 Node.js 的新手,我有一个使用 MySQL 数据库部署到 Heroku 的应用程序。

但是,我不断收到错误消息。该应用程序仅在我在 Heroku 上部署后才能运行一段时间。它突然停止工作,我收到以下错误:

   events.js:160
               throw er; // Unhandled 'error' event

   Error: Connection lost: The server closed the connection.
   at Protocol.end (/app/node_modules/mysql/lib/protocol/Protocol.js:113:13)
   at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:109:28)
   at emitNone (events.js:91:20)
   at Socket.emit (events.js:185:7)
   at endReadableNT (_stream_readable.js:974:12)
   at _combinedTickCallback (internal/process/next_tick.js:80:11)
   at process._tickCallback (internal/process/next_tick.js:104:9)
   State changed from up to crashed
   Process exited with status 1

这是我的代码:

  var express = require('express');
  var app = express();
  var mysql = require('mysql')
  var bodyParser = require('body-parser');
  const sortBy = require('sort-array')


  app.set('port', (process.env.PORT || 5000));
  app.set("view engine", "ejs");
  app.use(bodyParser.urlencoded({extended: true}));
  app.use(express.static(__dirname + '/public'));



  var db_config = {
  host: 'us-cdbr-iron-east-05.cleardb.net',
  user: 'REDACTED',
  password: 'REDACTED',
  database: 'heroku_REDACTED'
  };

 var connection;
 connection = mysql.createConnection(db_config); 

 var count2 = 10;
 var count3 = 20;
 var count4 = 10;
 //SELECT COUNT(*) AS count2 FROM photos

 app.get("/", function(req, res){
 var q_users = "SELECT COUNT(*) AS count1 FROM users";

 connection.query(q_users, function(err,results, fields){
 if(err) throw err;
 var count1 = results[0].count1;
 //res.send(results);
 res.render("home", {data1: count1, data2: count2, data3: count3, 
  data4: count4});
   });
  });



  app.post('/adduser', function(req,res){
  var person = { username: req.body.username};

   connection.query('INSERT INTO users SET ?', person, function(err, 
   result){
    if(err) throw err;
    res.redirect("/");

    });
    });




    app.post('/deleteuserid', function(req,res){
     var id = req.body.userid;

     connection.query('DELETE FROM users WHERE id = ?', id, function(err, result){
      if(err) throw err;
      //res.send(result);
      res.redirect("/countpictures");

      });
    });


  app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
  });

有人可以告诉我如何解决这个问题吗?我有很多 SQL 查询,并且我认为正在发生某种形式的超时。请告诉我应该进行哪些更改以避免此错误,以便我的应用程序稳定并且在每 5 分钟部署后不会崩溃。

4

2 回答 2

0

不幸的是,MySQL 在空闲太久后最终会关闭连接......

为避免这种情况,您需要使用连接池。连接池为您管理连接,并在必要时重新连接。有关连接池的更多详细信息,请参阅https://github.com/mysqljs/mysql#pooling-connections

因此,您可以通过将连接替换为以下内容来使您的代码更加健壮:

const connection = mysql.createPool({ connectionLimit: 5, ...db_config }); 

理想情况下,您还将连接变量重命名为pool ;)

于 2017-09-30T17:22:07.277 回答
0

我有同样的错误,我这样解决了

var mysql = require ('mysql');
var pool = mysql.createPool ({
  host: 'xxxx',
  user: 'xxxx',
  password: 'xxxx',
  database: 'xxxx'
});
module.exports = pool;
于 2021-04-22T11:08:44.010 回答