te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Node JS mysql database disconnect - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node JS mysql database disconnect - Stack Overflow

programmeradmin2浏览0评论

I am using Node JS and I am trying to connect to a mysql database. It keeps getting disconnected due to a timeout so I wrote a function to reconnect if it does timeout. Although I need it to be a continuous connection or references in my code won't work. Here is my relevant code:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : '.........', // MySQL Host
    user     : '.........', // MySQL User
    password : '.........', // MySQL Password
    database : '.........' // MySQL Databse
});

// MYSQL INFO

//connection.connect();

function replaceClientOnDisconnect(connection) {
  connection.on("error", function (err) {
    if (!err.fatal) {
      console.log('Databse Error, error not fatal');
      return;
    }

    if (err.code !== "PROTOCOL_CONNECTION_LOST") {
      throw err;
      console.log('PROTOCOL_CONNECTION_LOST Error: Reconnecting to database...');
    }

    setTimeout(function () {
        connection.destroy();
        connection = mysql.createConnection(connection.config);
        replaceClientOnDisconnect(connection);
        connection.connect(function (error) {
          if (error) {
            process.exit(1);
          } else {
              console.log('Reconnected to database!');
          }
    }, 1000); // 1 sec
    });
  });
}

// And run this on every connection as soon as it is created.
replaceClientOnDisconnect(connection);

I am using Node JS and I am trying to connect to a mysql database. It keeps getting disconnected due to a timeout so I wrote a function to reconnect if it does timeout. Although I need it to be a continuous connection or references in my code won't work. Here is my relevant code:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : '.........', // MySQL Host
    user     : '.........', // MySQL User
    password : '.........', // MySQL Password
    database : '.........' // MySQL Databse
});

// MYSQL INFO

//connection.connect();

function replaceClientOnDisconnect(connection) {
  connection.on("error", function (err) {
    if (!err.fatal) {
      console.log('Databse Error, error not fatal');
      return;
    }

    if (err.code !== "PROTOCOL_CONNECTION_LOST") {
      throw err;
      console.log('PROTOCOL_CONNECTION_LOST Error: Reconnecting to database...');
    }

    setTimeout(function () {
        connection.destroy();
        connection = mysql.createConnection(connection.config);
        replaceClientOnDisconnect(connection);
        connection.connect(function (error) {
          if (error) {
            process.exit(1);
          } else {
              console.log('Reconnected to database!');
          }
    }, 1000); // 1 sec
    });
  });
}

// And run this on every connection as soon as it is created.
replaceClientOnDisconnect(connection);
Share Improve this question asked May 23, 2016 at 8:11 user3391232user3391232
Add a ment  | 

2 Answers 2

Reset to default 12

You may use sample

var dbConfig = {
        host: '----',
        user: '----',
        password: '----',
        database: '----',
        port: ----
    };

var connection;
function handleDisconnect() {
    connection = mysql.createConnection(dbConfig);  // Recreate the connection, since the old one cannot be reused.
    connection.connect( function onConnect(err) {   // The server is either down
        if (err) {                                  // or restarting (takes a while sometimes).
            console.log('error when connecting to db:', err);
            setTimeout(handleDisconnect, 10000);    // 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 onError(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)
        }
    });
}
handleDisconnect();

Why don't you try using createPool function instead of createConnection

const connection = mysql.createPool(dbConfig);

connection.on('connection', () => console.log('db connected'));

connection.on('error', (err) => console.log(err));

And now your connection will not break automatically

发布评论

评论列表(0)

  1. 暂无评论