简体   繁体   English

如何处理 NodeJS 上的 MySQL 断开连接?

[英]How can I handle MySQL disconnection on NodeJS?

First of all, I'm a beginner on NodeJS.首先,我是 NodeJS 的初学者。 Well, I'm using a shared hosting to my project and when the database reaches 1 minute of inactivity, NodeJS crashes and disconnects me from MySQL.好吧,我对我的项目使用共享主机,当数据库达到 1 分钟不活动时,NodeJS 崩溃并断开我与 MySQL 的连接。 Since I'm using a shared hosting, I can't edit the idle time on the MySQL config and I'll need to handle it in code.由于我使用的是共享主机,我无法在 MySQL 配置上编辑空闲时间,我需要在代码中处理它。

I'm using module.exports to handle my connection, as shown below.我正在使用module.exports来处理我的连接,如下所示。 So how can I make an auto-reconnection script to take care of my issue?那么如何制作自动重新连接脚本来解决我的问题呢? Thank you.谢谢你。

var mysql = require('mysql');

module.exports =
{
handle: null,

connect: function(call){
    this.handle = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'test',
        timezone: 'utc',
        charset : 'utf8'
    });

    this.handle.connect(function (err) {
        if(err) {
            console.log("[MySQL] Connection error: " + err.code);
        } else {
            console.log("[MySQL] Successfully connected");
        }
    });
  }
};

The node mysql module that you are using also has a connection pooling mechanism.您正在使用的节点 mysql 模块也具有连接池机制。

Check out the docs at https://github.com/mysqljs/mysql#pooling-connectionshttps://github.com/mysqljs/mysql#pooling-connections查看文档

Connection pools will make you task easier.连接池将使您的任务更轻松。 You can then store the connection pool object and use its getConnection method to obtain a connection.然后您可以存储连接池对象并使用其getConnection方法来获取连接。 Make sure that you release the connection when you are done with it.确保在完成连接后释放连接。

If for some reason you cant use connection pooling then you will have to listen for error event on the connection and handle it accordingly.如果由于某种原因您不能使用连接池,那么您将不得不监听连接上的error事件并相应地处理它。 But I strongly recommend that you use connection pool.但我强烈建议您使用连接池。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM