Skip to content

Commit 92f8f72

Browse files
authored
Add a Redis PING every minute to keep the connection alive (#18584)
* Add a Redis PING every minute to keep the connection alive
1 parent 920daec commit 92f8f72

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

lib/redis/create-client.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,14 @@ module.exports = function createClient (options = {}) {
3434
}
3535
}
3636

37+
let pingInterval = null
38+
function stopPinging () {
39+
if (pingInterval) {
40+
clearInterval(pingInterval)
41+
pingInterval = null
42+
}
43+
}
44+
3745
// Create the client
3846
const client = Redis.createClient(url, {
3947
// Only add this configuration for TLS-enabled Redis URL values.
@@ -96,6 +104,26 @@ module.exports = function createClient (options = {}) {
96104
} catch (disconnectError) {
97105
// Swallow any failure
98106
}
107+
108+
// Also, stop pinging the Redis server
109+
stopPinging()
110+
})
111+
112+
client.on('connect', () => {
113+
// Stop pinging the Redis server, if any such timer already exists
114+
stopPinging()
115+
116+
// Start pinging the server once per minute to prevent Redis connection
117+
// from closing when its idle `timeout` configuration value expires
118+
pingInterval = setInterval(
119+
() => { client.ping(() => {}) },
120+
60 * 1000
121+
)
122+
})
123+
124+
client.on('end', () => {
125+
// Stop pinging the Redis server
126+
stopPinging()
99127
})
100128

101129
// If a `name` was provided, use it in the prefix for logging event messages

0 commit comments

Comments
 (0)