如何检查MySQL数据库是否已准备好从节点MySQL连接池进行某些查询?
我有一个由您的容器组成的Docker环境:
数据库容器运行一个MySQL数据库。 api容器连接到该数据库。所有三个容器同时启动。 Web服务器容器在0.5秒后启动。 api容器在2秒后启动。 20秒后数据库服务器启动。
当前,api会在数据库启动并运行之前尝试访问数据库的表。这会导致错误,例如拒绝连接。以下代码段始终以消息“错误查询数据库!”结尾。当MySQL数据库尚未启动时:
const sql: string = 'SELECT * FROM sometable;';
MySQL.createPool({
connectionLimit: 10,
acquireTimeout: 30000,
waitForConnections: true,
database: 'mydatabase',
host: 'localhost',
multipleStatements: true,
password: 'mypassword',
user: 'root',
}).query(sql, (err, result) => {
if (result) {
console.log('Successfully queried database.');
} else {
console.log('Error querying database!');
}
});
正在使用的版本:
OS: Ubuntu 19.10
Node: v13.6.0
MySQL (Node API): "@types/mysql": "2.15.8" and "mysql": "2.17.1"
MySQL (Docker Database): mysql:5.7.28
TypeScript: 3.7.4
我想从api中检查(并等待)数据库的就绪状态,可能使用我用于查询的连接池。有可能吗?
setTimeout()
:(用JavaScript而不是打字稿回答)
'use strict';
const dbpool = require('mysql').createPool({
connectionLimit: 10,
acquireTimeout: 30000,
waitForConnections: true,
database: 'mydatabase',
host: 'localhost',
multipleStatements: true,
password: 'mypassword',
user: 'root',
});
const sql = 'SELECT * FROM sometable;';
const attemptConnection = () =>
dbpool.getConnection((err, connection) => {
if (err) {
console.log('error connecting. retrying in 1 sec');
setTimeout(attemptConnection, 1000);
} else {
connection.query(sql, (errQuery, results) => {
connection.release();
if (errQuery) {
console.log('Error querying database!');
} else {
console.log('Successfully queried database.');
}
});
}
});
attemptConnection();
这是我的测试运行:
$ sudo service mysql stop; node test.js & sudo service mysql start
[1] 24737
error connecting. retrying in 1 sec
error connecting. retrying in 1 sec
$ Successfully queried database.
FYI,程序永远不会结束,因为它需要dbpool.end()
;