fix: implement db connection retry mechanism
All checks were successful
Build and Deploy / build-and-push (push) Successful in 2m16s
All checks were successful
Build and Deploy / build-and-push (push) Successful in 2m16s
This commit is contained in:
@@ -3,7 +3,7 @@ const mysql = require('mysql2/promise');
|
||||
|
||||
// Configuração da conexão com o banco de dados
|
||||
// Em produção, estes valores devem vir de variáveis de ambiente (.env)
|
||||
const pool = mysql.createPool({
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
user: process.env.DB_USER || 'root',
|
||||
password: process.env.DB_PASSWORD || 'password',
|
||||
@@ -11,16 +11,32 @@ const pool = mysql.createPool({
|
||||
waitForConnections: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0,
|
||||
});
|
||||
};
|
||||
|
||||
// Teste de conexão simples ao iniciar
|
||||
pool.getConnection()
|
||||
.then(connection => {
|
||||
console.log('✅ Conectado ao MySQL com sucesso!');
|
||||
connection.release();
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('❌ Erro ao conectar ao MySQL:', err.message);
|
||||
});
|
||||
const pool = mysql.createPool(dbConfig);
|
||||
|
||||
// Função para testar a conexão com retry
|
||||
const connectWithRetry = async (retries = 5, delay = 5000) => {
|
||||
for (let i = 0; i < retries; i++) {
|
||||
try {
|
||||
const connection = await pool.getConnection();
|
||||
console.log('✅ Conectado ao MySQL com sucesso!');
|
||||
connection.release();
|
||||
return; // Conexão bem-sucedida, sair da função
|
||||
} catch (err) {
|
||||
console.error(`❌ Erro ao conectar ao MySQL (Tentativa ${i + 1}/${retries}):`, err.message);
|
||||
if (i < retries - 1) {
|
||||
console.log(`⏳ Aguardando ${delay / 1000} segundos antes de tentar novamente...`);
|
||||
await new Promise(res => setTimeout(res, delay));
|
||||
} else {
|
||||
console.error('🚨 Falha crítica: Não foi possível conectar ao banco de dados após várias tentativas.');
|
||||
// Opcional: process.exit(1) se quiser que o container reinicie
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Iniciar a tentativa de conexão
|
||||
connectWithRetry();
|
||||
|
||||
module.exports = pool;
|
||||
|
||||
Reference in New Issue
Block a user