Skip to content

Instantly share code, notes, and snippets.

@ericmoritz
Created November 11, 2011 05:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericmoritz/1357279 to your computer and use it in GitHub Desktop.
Save ericmoritz/1357279 to your computer and use it in GitHub Desktop.
Premature redis cluster support for node.js
var redis = require("redis");
function randrange(stop) {
return Math.floor(Math.random() * stop * 1000 % stop)
}
function Cluster(hosts) {
var that = this;
var hosts = hosts || [];
this.clients = {};
function keymoved(err) {
if(err) {
var match = /^(MOVED|ASK) (\d+) (.+)/.exec(err.message);
if(match) {
return match.slice(2);
}
}
}
this.add_client = function(hostport) {
var bits = hostport.split(/:/),
host = bits[0],
port = bits[1],
client = that.clients[hostport] || redis.createClient(port, host);
return that.clients[hostport] = client;
}
this.random_client = function() {
var keys = Object.keys(that.clients),
client_count = keys.length,
i = randrange(client_count),
key = keys[i];
return that.clients[key];
}
this._mkcallback = function(callback) {
return function(err, result) {
var moved = keymoved(err);
if(moved) {
that._do(that.add_client(moved[1]), this.command, this.args, callback);
} else {
if(callback) {
callback.call(this, err, result);
}
}
}
}
this._do = function(client, command, args, callback) {
return client.send_command(command, args, that._mkcallback(callback));
}
this.do = function(command, args, callback) {
// Pick client at random
var client = that.random_client();
that._do(client, command, args, callback);
}
this.cb = function(callback) {
return that._mkcallback(callback);
}
hosts.forEach(this.add_client);
}
exports.Cluster = Cluster;
var Cluster = require('rediscluster').Cluster,
redis = require('redis');
var cluster = new Cluster(["localhost:6660"]);
var keys = ["osetuhaoseth", "aosteuhas", "oaesthaso"];
keys.forEach(function(key) {
var client = cluster.random_client();
client.set(key, Math.random(), cluster.cb(redis.print));
})
keys.forEach(function(key) {
var client = cluster.random_client();
client.get(key, cluster.cb(redis.print));
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment