added redis configuration

This commit is contained in:
2025-08-07 01:54:36 +05:30
parent 9093da6bc9
commit e9a001ecf6
3 changed files with 154 additions and 2 deletions

58
src/config/redis.js Normal file
View File

@@ -0,0 +1,58 @@
const { createClient } = require('redis');
const { redisUrl } = require('./config');
const { logger } = require('../util/logger');
const client = createClient({
url: redisUrl,
socket: {
reconnectStrategy: (retries) => {
const delay = Math.min(retries * 100, 5000);
logger.info(`Redis reconnecting attempt ${retries}, delay ${delay}ms`);
return delay;
},
},
});
client.on('connect', () => logger.info('Connected to redis'));
client.on('error', () => logger.error(err, 'Redis error'));
client.on('ready', () => logger.info('Redis client ready'));
client.on('end', () => logger.info('Redis connection closed'));
client
.connect()
.catch((err) => logger.error(err, 'Failed to connect to Redis'));
// Helper functions
async function setJson(key, value, ttl = null) {
try {
const jsonValue = JSON.stringify(value);
if (ttl) {
return await client.set(key, jsonValue, { EX: ttl });
}
return await client.set(key, jsonValue);
} catch (err) {
logger.error(err, 'Redis setJson error');
throw err;
}
}
async function getJson(key) {
try {
const value = await client.get(key);
return value ? JSON.parse(value) : null;
} catch (err) {
logger.error(err, 'Redis getJson error');
throw err;
}
}
process.on('SIGTERM', async () => {
logger.info('SIGTERM received - closing Redis connection');
await client.quit();
});
module.exports = {
client,
getJson,
setJson,
};