@@ -2,31 +2,55 @@ import { createClient } from 'redis';
2
2
import dotenv from 'dotenv' ;
3
3
dotenv . config ( ) ;
4
4
5
+ const REDIS_URL = process . env . REDIS_URL || 'redis://localhost:6379' ;
6
+
5
7
const redisClient = createClient ( {
6
- url : process . env . REDIS_URL || 'redis://127.0.0.1:6379' ,
8
+ url : REDIS_URL ,
7
9
socket : {
8
- reconnectStrategy : retries => Math . min ( retries * 50 , 2000 ) ,
10
+ reconnectStrategy : retries => {
11
+ console . warn ( `🔁 Redis reconnect attempt #${ retries } ` ) ;
12
+ return Math . min ( retries * 100 , 3000 ) ; // retry with backoff
13
+ } ,
9
14
} ,
10
15
} ) ;
11
16
12
- redisClient . on ( 'error' , err => console . error ( '❌ Redis Client Error:' , err ) ) ;
13
- redisClient . on ( 'connect' , ( ) => console . log ( '✅ Redis connected' ) ) ;
14
- redisClient . on ( 'reconnecting' , ( ) => console . log ( '♻️ Redis reconnecting...' ) ) ;
17
+ redisClient . on ( 'error' , err => {
18
+ console . error ( '❌ Redis Client Error:' , err . message ) ;
19
+ } ) ;
20
+
21
+ redisClient . on ( 'connect' , ( ) => {
22
+ console . log ( '✅ Redis connected' ) ;
23
+ } ) ;
24
+
25
+ redisClient . on ( 'ready' , ( ) => {
26
+ console . log ( '🟢 Redis ready' ) ;
27
+ } ) ;
28
+
29
+ redisClient . on ( 'reconnecting' , ( ) => {
30
+ console . log ( '🔄 Redis reconnecting...' ) ;
31
+ } ) ;
15
32
16
33
const connectWithRetry = async ( retries = 5 ) => {
17
- while ( retries ) {
34
+ while ( retries > 0 ) {
18
35
try {
19
36
await redisClient . connect ( ) ;
20
- console . log ( '✅ Connected to Redis ' ) ;
37
+ console . log ( '🚀 Redis connection established ' ) ;
21
38
return redisClient ;
22
39
} catch ( err ) {
23
- console . error ( ' ⏳ Redis connection failed, retrying in 3s...' ) ;
40
+ console . error ( ` ⏳ Redis connection failed: ${ err . message } ` ) ;
24
41
retries -- ;
25
42
await new Promise ( res => setTimeout ( res , 3000 ) ) ;
26
43
}
27
44
}
28
- throw new Error ( '❌ Could not connect to Redis after retries ' ) ;
45
+ throw new Error ( '❌ Redis not reachable after multiple attempts ' ) ;
29
46
} ;
30
47
31
48
await connectWithRetry ( ) ;
49
+
50
+ process . on ( 'SIGINT' , async ( ) => {
51
+ await redisClient . quit ( ) ;
52
+ console . log ( '👋 Redis client closed' ) ;
53
+ process . exit ( 0 ) ;
54
+ } ) ;
55
+
32
56
export default redisClient ;
0 commit comments