nodejs 连接远程MySql数据库 出现自动断开问题

参照网上这段代码还是不能解决问题,本地连接不会出现断开,求大神们讲解

    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)  
        }  
      });  

      return connection;
    }  
  
    handleDisconnect();  
阅读 3.9k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进