2017-09-30 54 views
0

我是Node.js的新手,我有一個應用程序,我使用MySQL數據庫部署到Heroku。具有部署在heroku上的MySQL數據庫的Node.js應用程序不斷崩潰

但是,我不斷收到錯誤。 該應用程序僅在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分鐘部署後不會崩潰。

+0

請沒有安全憑證。立即更改密碼** ** –

+0

sry..will照顧未來!非常感謝 – kritttt

回答

0

不幸的是,MySQL將最終關閉連接它已經閒置太久後...

爲了避免這種情況,你需要使用連接池。連接池爲您管理連接,必要時重新連接。有關連接池的更多詳細信息,請參閱https://github.com/mysqljs/mysql#pooling-connections

因此,你可以讓你的代碼更健壯通過更換具有以下連接:

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

理想情況下,你也想重命名連接變量爲好;)