Skip to content

Feature: Allows overriding a getServer method for using a hashring #159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add the usage example to the comment?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just added the example, let me know if it needs changing, thanks!

//
// 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