Created
July 19, 2018 21:20
-
-
Save CarlosMecha/88b3fe634a49c83223c1e82382d34c8b to your computer and use it in GitHub Desktop.
Redis reconnect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const redis = require('redis') | |
const util = require('util') | |
const backoff = require('backoff') | |
const interval = 1000 | |
const port = process.env.REDIS_PORT || '6379' | |
const host = process.env.REDIS_HOST || 'localhost' | |
const b = new backoff.ExponentialStrategy({ | |
initialDelay: 1000, | |
maxDelay: 60 * 1000 | |
}) | |
const client = redis.createClient({ | |
host: host, | |
port: parseInt(port), | |
retry_strategy: reconnect | |
}) | |
function reconnect(options) { | |
console.log(util.format('%s: Reconnect with options %s', new Date().toLocaleString(), util.inspect(options))) | |
return b.next() | |
} | |
function doStuff () { | |
client.keys('*', (err, keys) => { | |
console.log(util.format('%s: Redis keys -> %s', new Date().toLocaleString(), util.inspect(keys))) | |
}) | |
} | |
function logEvent (event) { | |
return () => console.log(util.format('%s: Redis event -> %s', new Date().toLocaleString(), event)) | |
} | |
client.on('ready', () => { | |
logEvent('ready') | |
client.set("test", "this is a test", (err) => { | |
if (err) { | |
console.log("Error communicating with redis") | |
return | |
} | |
setInterval(doStuff, interval) | |
}) | |
}) | |
client.on('error', () => logEvent('error')) | |
client.on('reconnect', () => { | |
logEvent('reconnect')() | |
b.reset() | |
}) | |
client.on('connect', () => logEvent('connect')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment