A simple, pure JS implementation of consistent hashing.
npm install consistent-hashring
const ConsistentHashRing = require('consistent-hashring');
let hashring = new ConsistentHashRing();
for (let i = 0; i < 10; i++) {
hashring.addNode('node_' + i);
}
const nodeForKeyA = hashring.getNode('A');
const nodeForKeyB = hashring.getNode('B');
hashring.removeNode('node_50');
hashring.removeNode('node_90');
By default, 100 replicas of each node are distributed around the ring.
You can change this by passing a replicaCount
as the second parameter of addNode
:
hashring.addNode('nodeA', 50); //half the default weight
hashring.addNode('nodeB', 200); //twice the default weight
By default, a ConsistentHashRing
uses
Gary Court's murmurhash3_32_gc implementation
for hashing.
You can modify test/test.js
and run npm run test
to see how
well your hash function distributes.
You can inject your own hashing algorithm when instantiating a ConsistentHashRing
const myGreatHashFunction = function(str) {
//return some hash of str
};
let hashring = new ConsistentHashRing(myGreatHashFunction);