Im trying to configure master slave in nodejs web. I want to connect to the slave server when the master one is collapsed. I tried to stop the master and it really connected to the slave. However, when i signed in on the web, the web crashed. How should i fix this?
Here is the code
let db = null;
function createDatabaseConnection() {
if (!db) {
db = mysql.createConnection(master);
db.on('error', (err) => {
console.error('Cant connect to master server:', err);
console.log('Change to slave server.');
db = mysql.createConnection(slave);
reconnect(db);
});
}
return db;
}
function reconnect(connection) {
connection.connect((err) => {
if (err) {
console.error('Cant connect to slave server:', err);
} else {
console.log('Connected to slave server.');
}
});
connection.on('error', (err) => {
console.error('Cant connect to slave server:', err);
});
}
module.exports = createDatabaseConnection();
Here is the error
Cant connect to master server: AggregateError
at internalConnectMultiple (node:net:1114:18)
at afterConnectMultiple (node:net:1667:5) {
code: 'ECONNREFUSED',
fatal: true,
[errors]: [
Error: connect ECONNREFUSED ::1:3306
at createConnectionError (node:net:1634:14)
at afterConnectMultiple (node:net:1664:40) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 3306
},
Error: connect ECONNREFUSED 127.0.0.1:3306
at createConnectionError (node:net:1634:14)
at afterConnectMultiple (node:net:1664:40) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306
}
]
}
Change to slave server.
Connected to slave server.
[]
C:UsersAdminsourcereposHotelBookingnode_modulesmysql2libconnection.js:164
const err = new Error(
^
Error: Can't add new command when connection is in closed state
New contributor
Nguyễn Trangg is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.