forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis.js
More file actions
115 lines (101 loc) · 2.82 KB
/
Copy pathredis.js
File metadata and controls
115 lines (101 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import { createClient } from "redis";
import logger from "./logger.js";
let redisClient = null;
let isReady = false;
/**
* Initialize Redis client
*/
export const initRedis = async () => {
try {
// Create Redis client with cloud credentials
const redisConfig = process.env.REDIS_URL
? {
// Use connection URL if provided
url: process.env.REDIS_URL,
socket: {
reconnectStrategy: (retries) => {
if (retries > 10) {
logger.error("❌ Redis max reconnection attempts reached");
return new Error("Redis max reconnection attempts");
}
return Math.min(retries * 100, 3000);
},
},
}
: {
// Use separate credentials (Redis Cloud format)
username: process.env.REDIS_USERNAME || "default",
password: process.env.REDIS_PASSWORD,
socket: {
host: process.env.REDIS_HOST || "localhost",
port: parseInt(process.env.REDIS_PORT || "6379"),
reconnectStrategy: (retries) => {
if (retries > 10) {
logger.error("❌ Redis max reconnection attempts reached");
return new Error("Redis max reconnection attempts");
}
return Math.min(retries * 100, 3000);
},
},
};
redisClient = createClient(redisConfig);
// Error handling
redisClient.on("error", (err) => {
logger.error("Redis Client Error:", err);
isReady = false;
});
redisClient.on("connect", () => {
logger.info("🔄 Redis connecting...");
});
redisClient.on("ready", () => {
logger.info("✅ Redis connected and ready");
isReady = true;
});
redisClient.on("reconnecting", () => {
logger.warn("⚠️ Redis reconnecting...");
isReady = false;
});
redisClient.on("end", () => {
logger.warn("⚠️ Redis connection closed");
isReady = false;
});
// Connect to Redis
await redisClient.connect();
return redisClient;
} catch (error) {
logger.error("❌ Failed to connect to Redis:", error);
// Don't throw error - app can work without Redis
return null;
}
};
/**
* Get Redis client instance
*/
export const getRedisClient = () => {
return redisClient;
};
/**
* Check if Redis is ready
*/
export const isRedisReady = () => {
return isReady && redisClient?.isOpen;
};
/**
* Graceful shutdown
*/
export const closeRedis = async () => {
try {
if (redisClient && redisClient.isOpen) {
await redisClient.quit();
logger.info("✅ Redis connection closed gracefully");
}
} catch (error) {
logger.error("Error closing Redis connection:", error);
}
};
export default {
initRedis,
getRedisClient,
isRedisReady,
closeRedis,
};