| 1 | import Redis from 'ioredis'; |
| 2 | |
| 3 | import { env } from '@/config/env'; |
| 4 | import { logger } from '@/utils/logger'; |
| 5 | |
| 6 | let redis: Redis | null = null; |
| 7 | |
| 8 | export const getRedisClient = (): Redis => { |
| 9 | if (!redis) { |
| 10 | redis = new Redis(env.REDIS_URL, { lazyConnect: true }); |
| 11 | |
| 12 | redis.on('error', (error) => { |
| 13 | logger.error({ err: error }, 'Redis connection error'); |
| 14 | }); |
| 15 | |
| 16 | redis.on('connect', () => { |
| 17 | logger.info('Redis connection established'); |
| 18 | }); |
| 19 | |
| 20 | redis.on('reconnect', () => { |
| 21 | logger.info('Redis reconnecting...'); |
| 22 | }); |
| 23 | |
| 24 | redis.on('close', () => { |
| 25 | logger.warn('Redis connection closed'); |
| 26 | }); |
| 27 | } |
| 28 | |
| 29 | return redis; |
| 30 | }; |
| 31 | |
| 32 | export const connectRedis = async () => { |
| 33 | const client = getRedisClient(); |
| 34 | if (client.status === 'ready' || client.status === 'connecting') { |
| 35 | return; |
| 36 | } |
| 37 | await client.connect(); |
| 38 | }; |
| 39 | |
| 40 | export const closeRedis = async () => { |
| 41 | if (!redis) { |
| 42 | return; |
| 43 | } |
| 44 | |
| 45 | await redis.quit(); |
| 46 | redis = null; |
| 47 | }; |