node-mysql pool experiences ETIMEDOUT

2019-03-03 07:17发布

问题:

I have a node-mysql pool configuration of

var db_init={
            host     : 'ip_address_of_GCS_SQL',
            user     : 'user_name_of_GCS_SQL',
            password : 'password here',
            database : 'db here',
            supportBigNumbers: true,
            connectionLimit:100
};

Pool was created using

GLOBAL.db_foobar = mysql.createPool(db_init);

I basically just left the connection on for a couple of hours and I saw this error reported by my connection.query Request (after getConnection of course):

prodAPI-104 (out): { status: 'Error',
prodAPI-104 (out):   details: '[foobar_function]Error in query',
prodAPI-104 (out):   err: '{ [Error: read ETIMEDOUT]\n  code: \'ETIMEDOUT\',\n      errno: \'ETIMEDOUT\',\n  syscall: \'read\',\n  fatal: true }',
prodAPI-104 (out):   query: 'SELECT * FROM `foobar_table`;' }

Why is this happening? The MySQL in Google-Cloud-SQL didn't report a query taking too long to create so I dunno why this happened.

回答1:

I suspect the reason is that keepalive is not enabled on the connection to the MySQL server.

node-mysql does not have an option to enable keepalive and neither does node-mysql2, but node-mysql2 provides a way to supply a custom function for creating sockets which we can use to enable keepalive:

var mysql = require('mysql2');
var net = require('net');

var pool  = mysql.createPool({
  connectionLimit : 100,
  host            : '123.123.123.123',
  user            : 'foo',
  password        : 'bar',
  database        : 'baz',
  stream          : function(opts) {
    var socket = net.connect(opts.config.port, opts.config.host);
    socket.setKeepAlive(true);
    return socket;
  }
});