-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathredis-manager.service.ts
More file actions
101 lines (89 loc) · 2.96 KB
/
redis-manager.service.ts
File metadata and controls
101 lines (89 loc) · 2.96 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
import { Injectable, Logger, OnApplicationShutdown } from "@nestjs/common";
import IORedis, { Redis, RedisOptions } from "ioredis";
import { ConfigService } from "@nestjs/config";
import { RedisConfig } from "../../configs/types/RedisConfig";
@Injectable()
export class RedisManagerService implements OnApplicationShutdown {
private config: RedisConfig;
protected connections: {
[key: string]: Redis;
} = {};
private healthCheckIntervals: {
[key: string]: NodeJS.Timeout;
} = {};
constructor(
private readonly logger: Logger,
private readonly configService: ConfigService,
) {
this.config = this.configService.get("redis");
}
onApplicationShutdown() {
for (const [, interval] of Object.entries(this.healthCheckIntervals)) {
clearInterval(interval);
}
for (const [, conn] of Object.entries(this.connections)) {
conn.disconnect();
}
}
public getConnection(connection = "default"): Redis {
if (!this.connections[connection]) {
const currentConnection: Redis = (this.connections[connection] =
new IORedis(this.getConfig(connection)));
currentConnection.on("error", (error) => {
if (
!error.message.includes("ECONNRESET") &&
!error.message.includes("EPIPE") &&
!error.message.includes("ETIMEDOUT")
) {
this.logger.error("redis error", error);
}
});
/**
* We may get disconnected, and we may need to force a re-connect.
*/
const pingTimeoutError = `did not receive ping in time (5 seconds)`;
currentConnection.on("online", () => {
if (this.healthCheckIntervals[connection]) {
clearInterval(this.healthCheckIntervals[connection]);
}
this.healthCheckIntervals[connection] = setInterval(async () => {
if (currentConnection.status === "ready") {
await new Promise(async (resolve, reject) => {
const timer = setTimeout(() => {
this.logger.warn(pingTimeoutError);
reject(new Error(pingTimeoutError));
}, 5000);
await currentConnection.ping(() => {
clearTimeout(timer);
resolve(true);
});
}).catch((error) => {
if (error.message !== pingTimeoutError) {
this.logger.error("error", error);
}
currentConnection.disconnect(true);
});
}
}, 5000);
});
}
return this.connections[connection];
}
public getConfig(connection: string): RedisOptions {
return Object.assign(
{},
{
enableReadyCheck: false,
enableOfflineQueue: true,
maxRetriesPerRequest: null,
showFriendlyErrorStack: !!process.env.DEV,
// our startup probe fails after 60 seconds
retryAttempts: 22,
retryStrategy() {
return 5 * 1000;
},
},
this.config.connections[connection],
);
}
}