Adding an initial connection timeout of 5 seconds which after it will retry again.

This commit is contained in:
mike12345567 2021-05-24 16:30:24 +01:00
parent 3873d12476
commit 3a9a32f5f6
1 changed files with 14 additions and 0 deletions

View File

@ -4,6 +4,7 @@ const Redis = env.isTest() ? require("ioredis-mock") : require("ioredis")
const { addDbPrefix, removeDbPrefix, getRedisOptions } = require("./utils") const { addDbPrefix, removeDbPrefix, getRedisOptions } = require("./utils")
const RETRY_PERIOD_MS = 2000 const RETRY_PERIOD_MS = 2000
const STARTUP_TIMEOUT_MS = 5000
const CLUSTERED = false const CLUSTERED = false
// for testing just generate the client once // for testing just generate the client once
@ -15,7 +16,10 @@ let CLIENT = env.isTest() ? new Redis(getRedisOptions()) : null
* will return the ioredis client which will be ready to use. * will return the ioredis client which will be ready to use.
*/ */
function init() { function init() {
let timeout
function errorOccurred(err) { function errorOccurred(err) {
// always clear this on error
clearTimeout(timeout)
CONNECTED = false CONNECTED = false
console.error("Redis connection failed - " + err) console.error("Redis connection failed - " + err)
setTimeout(() => { setTimeout(() => {
@ -26,6 +30,14 @@ function init() {
if (env.isTest() || (CLIENT && CONNECTED)) { if (env.isTest() || (CLIENT && CONNECTED)) {
return return
} }
// start the timer - only allowed 5 seconds to connect
timeout = setTimeout(() => {
if (!CONNECTED) {
errorOccurred()
}
}, STARTUP_TIMEOUT_MS)
// disconnect any lingering client
if (CLIENT) { if (CLIENT) {
CLIENT.disconnect() CLIENT.disconnect()
} }
@ -35,6 +47,7 @@ function init() {
} else { } else {
CLIENT = new Redis(opts) CLIENT = new Redis(opts)
} }
// attach handlers
CLIENT.on("end", err => { CLIENT.on("end", err => {
errorOccurred(err) errorOccurred(err)
}) })
@ -42,6 +55,7 @@ function init() {
errorOccurred(err) errorOccurred(err)
}) })
CLIENT.on("connect", () => { CLIENT.on("connect", () => {
clearTimeout(timeout)
CONNECTED = true CONNECTED = true
}) })
} }