当没有对mysql的请求时,我将遇到此错误,它将进入空闲状态,而我们将遇到此db错误。我正在使用节点,将mysql部署到openshift集群上。
如何使数据库连接保持活动状态,以使服务器永不关闭连接? PFA 请让我知道有什么解决方案吗?我被困了两个星期了
更新- 以下是我正在使用的代码
`var connection;
function handleDisconnect() {
connection = mysql.createConnection({
host: config.db.host,
user: config.db.user,
password: config.db.password,
database: config.db.database,
port: config.db.port,
}); // 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)
}
});
}
handleDisconnect();`
答案 0 :(得分:0)
由于使用的是Node.js,因此可以使用连接池。
以下是该链接的摘录。请注意,connection.release();
不会破坏连接,但允许再次使用该连接。
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
// Use the connection
connection.query('SELECT something FROM sometable', function (error, results, fields) {
// When done with the connection, release it.
connection.release();
// Handle error after the release.
if (error) throw error;
// Don't use the connection here, it has been returned to the pool.
});
});