【发布时间】:2022-02-04 20:22:43
【问题描述】:
我们的堆栈是带有 MySQL 的 nodejs,我们使用 MySQL 连接池化我们的 MySQL 数据库在 AWS aurora 上进行管理。 在自动故障转移的情况下,主数据库被更改,主机名保持不变,但池内的连接保持连接到错误的数据库。 我们发现重置连接的唯一原因是滚动我们的服务器。
这是我认为可以解决此问题的解决方案的演示 但我更喜欢没有设置间隔的解决方案
const mysql = require('mysql');
class MysqlAdapter {
constructor() {
this.connectionType = 'MASTER';
this.waitingForAutoFaileOverSwitch = false;
this.poolCluster = mysql.createPoolCluster();
this.poolCluster.add(this.connectionType, {
host: 'localhost',
user: 'root',
password: 'root',
database: 'app'
});
this.intervalID = setInterval(() => {
if(this.waitingForAutoFaileOverSwitch) return;
this.excute('SHOW VARIABLES LIKE \'read_only\';').then(res => {
// if MASTER is set to read only is on then its mean a fail over is accoure and swe need to switch all connection in poll to secondry database
if (res[0].Value === 'ON') {
this.waitingForAutoFaileOverSwitch = true
this.poolCluster.end(() => {
this. waitingForAutoFaileOverSwitch = false
});
};
});
}, 5000);
}
async excute(query) {
// delay all incoming request until pool kill all connection to read only database
if (this.waitingForAutoFaileOverSwitch) {
return new Promise((resolve, reject) => {
setTimeout(() => {
this.excute(query).then(res => {
resolve(res);
});
}, 1000);
});
}
return new Promise((resolve, reject) => {
this.poolCluster.getConnection(this.connectionType, (err, connection) => {
if (err) {
reject(err);
}
connection.query(query, (err, rows) => {
connection.release();
if (err) {
reject(err);
}
resolve(rows);
});
});
});
}
}
const adapter = new MysqlAdapter();
还有其他可编程的方式来重置池内的连接吗?
如果发生自动故障转移,我们可以列出任何通知吗?
【问题讨论】:
-
我们必须实现一个非开源包来测试我们是否连接到集群的写入或只读节点,如果它检测到故障转移 - 它会从池中删除所有连接 - iirc正确的问题是一个尝试写入只读实例的连接将被从池中逐出,但是一旦它到达最后一个连接,它就不会终止该连接,但随后的新连接将被定向到新的连接正确的主人。另一种选择是传播致命的写入错误(如果您可以容忍丢失)并让您的应用崩溃。
-
取决于从池中请求新连接的频率/并发性,即对连接的请求是检索到旧连接还是导致重新创建新连接,将指示连接的频率观察到的错误
-
为什么不使用 Amazon RDS 代理?
-
我已经在使用 haproxy
标签: mysql node.js amazon-web-services amazon-aurora