Last active
March 22, 2016 21:03
-
-
Save Stahlneckr/57d874bb899762c136a1 to your computer and use it in GitHub Desktop.
Heartbeat for Redis in NodeJS
This file contains hidden or 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
| // options: | |
| // { "interval": {time between pings in ms}, "maxTimespan": {acceptable lag between ping and pong}, "maxMisses": {number of misses before an error} } | |
| // events: | |
| // ping, pong(timespan), stop | |
| // miss(misses, error) - no pong in timespan | |
| // error(error) - number of misses > maxMisses or redis error | |
| var events = require("events"); | |
| var util = require("util"); | |
| module.exports = function HeartBeat(client, options) { | |
| options = options || {}; | |
| options.interval = options.interval || 1000; | |
| options.maxTimespan = options.maxTimespan || 500; | |
| options.maxMisses = options.maxMisses || 4; | |
| var misses = 0; | |
| var emitter = new events.EventEmitter(); | |
| var interval = setInterval(function() { | |
| emitter.emit("ping"); | |
| var begin = (new Date()).getTime(); | |
| var timedout = false; | |
| var timeout = setTimeout(function() { | |
| timedout = true; | |
| misses += 1; | |
| emitter.emit("miss", misses, new Error("Timed out")); | |
| if (misses >= options.maxMisses) { | |
| emitter.emit("error", new Error("More misses than allowed")); | |
| emitter.stop(); | |
| } | |
| }, options.maxTimespan); | |
| client.PING(function(err, res) { | |
| var timespan = (new Date()).getTime() - begin; | |
| clearTimeout(timeout); | |
| if (err) { | |
| misses += 1; | |
| emitter.emit("miss", misses, err); | |
| if (misses >= options.maxMisses) { | |
| emitter.emit("error", new Error("More misses than allowed")); | |
| emitter.stop(); | |
| } | |
| } | |
| else { | |
| if (res === "PONG") { | |
| if (timedout === false) { | |
| misses = 0; | |
| emitter.emit("pong", timespan); | |
| } | |
| } | |
| } | |
| }); | |
| }, options.interval); | |
| emitter.stop = function() { | |
| clearInterval(interval); | |
| emitter.emit("stop"); | |
| }; | |
| return emitter; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment