数据库
首页 > 数据库> > javascript-关闭MySQL后再打开,Node.js进程无法恢复

javascript-关闭MySQL后再打开,Node.js进程无法恢复

作者:互联网

我将Node.js与MySQL一起使用并进行了reify.

我有以下代码作为REST API的一部分运行.它工作正常.

server.get('/test', function (req, res, next) {
    var query_string =
        "SELECT DATE(date_transacted) AS transaction_date, " +
        " MonthReports.tb AS MonthReports__tb " +
        " FROM monthly_reports MonthReports " +
        " WHERE ( date_transacted >= \'2015-01-00\' AND date_transacted <= \'2015-09-00\' ) ";

    connection.query(
        query_string
        , function (err, rows, fields) {
            if (err) throw err;
            res.send(rows);
        });
});

如果我故意关闭MySQL数据库并进行REST API调用(该查询将运行查询),则会收到错误消息

Cannot enqueue Query after fatal error.

至此,我打开了MySQL数据库.我进行REST API调用时,node.js进程无法恢复,并且始终出现相同的错误. REST API服务器已死.

如何使Node.js REST API服务器代码可恢复?

解决方法:

我假设您正在脚本中进行全局连接.

一种简单的方法是为每个请求创建一个连接:

server.get('/test', function (req, res, next) {
    var query_string =
        "SELECT DATE(date_transacted) AS transaction_date, " +
        " MonthReports.tb AS MonthReports__tb " +
        " FROM monthly_reports MonthReports " +
        " WHERE ( date_transacted >= \'2015-01-00\' AND date_transacted <= \'2015-09-00\' ) ";



    var connection = getConnection(function connected(err) {
        if (err) {
           // error connecting  to mysql! alert user
        } else {
          connection.query(
            query_string
            , function (err, rows, fields) {
              if (err) throw err;
              res.send(rows);
          });
        }
    });

});

上面的代码是伪代码,因为我对节点mysql库不熟悉.这将允许每个请求查看mysql是否能够连接,以每个Web请求具有连接为代价.

另一种策略可能是在发出查询时检查err,如果有错误,请尝试重新建立全局连接.

server.get('/test', function (req, res, next) {
    var query_string =
        "SELECT DATE(date_transacted) AS transaction_date, " +
        " MonthReports.tb AS MonthReports__tb " +
        " FROM monthly_reports MonthReports " +
        " WHERE ( date_transacted >= \'2015-01-00\' AND date_transacted <= \'2015-09-00\' ) ";

    connection.query(
        query_string
        , function (err, rows, fields) {
            if (err) {
              // Try to reconnect here instead of throwing error and stopping node process, and reissue query
            }
            res.send(rows);
        });
});

标签:node-js,rest,restify,javascript,mysql
来源: https://codeday.me/bug/20191119/2036282.html