redis.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { createClient } from 'redis';
  2. import { config } from './index.js';
  3. import { logger } from '../utils/logger.js';
  4. export type RedisClient = ReturnType<typeof createClient>;
  5. let redisClient: RedisClient | null = null;
  6. export async function initRedis(): Promise<RedisClient> {
  7. if (redisClient) {
  8. return redisClient;
  9. }
  10. redisClient = createClient({
  11. socket: {
  12. host: config.redis.host,
  13. port: config.redis.port,
  14. connectTimeout: 5000,
  15. reconnectStrategy: (retries) => {
  16. if (retries > 3) {
  17. return new Error('Redis connection failed after 3 retries');
  18. }
  19. return Math.min(retries * 100, 3000);
  20. },
  21. },
  22. password: config.redis.password || undefined,
  23. database: config.redis.db,
  24. });
  25. redisClient.on('error', (err) => {
  26. logger.error('Redis Client Error:', err.message);
  27. });
  28. redisClient.on('connect', () => {
  29. logger.info('Redis Client Connected');
  30. });
  31. await redisClient.connect();
  32. return redisClient;
  33. }
  34. export function getRedisClient(): RedisClient {
  35. if (!redisClient) {
  36. throw new Error('Redis client not initialized');
  37. }
  38. return redisClient;
  39. }
  40. export async function closeRedis(): Promise<void> {
  41. if (redisClient) {
  42. await redisClient.quit();
  43. redisClient = null;
  44. }
  45. }