Skip to content

Commit

Permalink
Merge pull request #159 from sparkida/feat/find-server-override
Browse files Browse the repository at this point in the history
Feature: Allows overriding a getServer method for using a hashring
  • Loading branch information
saschat authored Jan 14, 2022
2 parents bd59195 + 0c827a8 commit 4ba76d0
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions lib/memjs/memjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,33 @@ Client.create = function(serversStr, options) {
return new Client(servers, options);
};

// An overridable method you can use for determing
// server selection. Should return the server index
// in the list of servers on Client#servers.
//
// Example using node-hashring:
// ~~~~
// const memjs = require('memjs');
// const HashRing = require('node-hashring');
// const servers = ['localhost:11211', 'localhost:11212'];
// // build a map of server addresses to their index in the server list
// const serverMap = {};
// servers.forEach((server, index) => serverMap[server] = index);
// const client = memjs.Client.create(servers.join(','));
// // build the hashring
// const hashRing = new HashRing(servers);
// // override the getServer method
// client.getServer = (key) => serverMap[hashRing.findNode(key)];
// ~~~~
Client.prototype.getServer = function(key) {
return hashCode(key) % this.servers.length;
};

// Chooses the server to talk to by hashing the given key.
Client.prototype.server = function(key) {
// TODO(alevy): should use consistent hashing and/or allow swapping hashing
// mechanisms
var total = this.servers.length;
var origIdx = (total > 1) ? (hashCode(key) % total) : 0;
var origIdx = total > 1 ? this.getServer(key) : 0;
var idx = origIdx;
var serv = this.servers[idx];
while (serv.wakeupAt &&
Expand Down

0 comments on commit 4ba76d0

Please sign in to comment.