const redis = require('redis');
const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { try { const pong = await pingAsync(); if (pong === 'PONG') { console.log('Redis connection is healthy'); } else { console.log('Unexpected response from Redis:', pong); await reconnect(); } } catch (err) { console.error('Redis connection error:', err); await reconnect(); } } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { client.quit(); client.connect((err) => { if (err) { console.error('Failed to reconnect to Redis:', err); reject(err); } else { console.log('Reconnected to Redis'); resolve(); } }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });- Use the following code to check the connection and reconnect if necessary:
const redis = require('redis');
const { promisify } = require('util');
// Create a Redis client with a connection timeout (in milliseconds)
const client = redis.createClient({
host: '127.0.0.1', // Replace with your Redis server host
port: 6379, // Replace with your Redis server port if different from default
connect_timeout: 10000 // 10 seconds timeout
});
// Promisify the `ping` method to check connection
const pingAsync = promisify(client.ping).bind(client);
// Function to check if connection is available and reconnect if not
async function ensureConnection() {
try {
const pong = await pingAsync();
if (pong === 'PONG') {
console.log('Redis connection is healthy');
} else {
console.log('Unexpected response from Redis:', pong);
await reconnect();
}
} catch (err) {
console.error('Redis connection error:', err);
await reconnect();
}
}
// Function to reconnect to Redis
async function reconnect() {
return new Promise((resolve, reject) => {
// Quit the current client
client.quit(() => {
// Create a new client instance
const newClient = redis.createClient({
host: '127.0.0.1', // Replace with your Redis server host
port: 6379, // Replace with your Redis server port if different from default
connect_timeout: 10000 // 10 seconds timeout
});
// Handle connection events for the new client
newClient.on('connect', () => {
console.log('Reconnected to Redis');
resolve(newClient);
});
newClient.on('error', (err) => {
console.error('Failed to reconnect to Redis:', err);
reject(err);
});
// Replace the old client with the new client
client = newClient;
});
});
}
// Example usage: Check connection and reconnect if necessary
ensureConnection()
.then(() => {
console.log('Connection check complete');
})
.catch(err => {
console.error('Error during connection check:', err);
});
// Close the connection gracefully on process exit
process.on('exit', () => {
client.quit();
});
client.on('error', (err) => {
console.error('Redis error:', err);
});
++++++++++++++++++++++++++++++++++++++++++++++++++++
3.
With timeout
const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) let client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Connection check timed out')); }, 5000); // 5 seconds timeout for the connection check pingAsync().then(pong => { clearTimeout(timeout); if (pong === 'PONG') { console.log('Redis connection is healthy'); resolve(); } else { console.log('Unexpected response from Redis:', pong); reconnect().then(resolve).catch(reject); } }).catch(err => { clearTimeout(timeout); console.error('Redis connection error:', err); reconnect().then(resolve).catch(reject); }); }); } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Reconnection timed out')); }, 10000); // 10 seconds timeout for reconnection // Quit the current client client.quit(() => { // Create a new client instance client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Handle connection events for the new client client.on('connect', () => { clearTimeout(timeout); console.log('Reconnected to Redis'); resolve(); }); client.on('error', (err) => { clearTimeout(timeout); console.error('Failed to reconnect to Redis:', err); reject(err); }); }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });
const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) let client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Connection check timed out')); }, 5000); // 5 seconds timeout for the connection check pingAsync().then(pong => { clearTimeout(timeout); if (pong === 'PONG') { console.log('Redis connection is healthy'); resolve(); } else { console.log('Unexpected response from Redis:', pong); reconnect().then(resolve).catch(reject); } }).catch(err => { clearTimeout(timeout); console.error('Redis connection error:', err); reconnect().then(resolve).catch(reject); }); }); } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Reconnection timed out')); }, 10000); // 10 seconds timeout for reconnection // Quit the current client client.quit(() => { // Create a new client instance client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Handle connection events for the new client client.on('connect', () => { clearTimeout(timeout); console.log('Reconnected to Redis'); resolve(); }); client.on('error', (err) => { clearTimeout(timeout); console.error('Failed to reconnect to Redis:', err); reject(err); }); }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });
No comments:
Post a Comment