Package hash;
Import Java.nio.ByteBuffer;
Import Java.nio.ByteOrder;
Import java.util.List;
Import Java.util.SortedMap;
Import Java.util.TreeMap;
public class Shard {
Private Treemap<long, string> nodes; Virtual node
Private list<string> shards; Real Machine node
Private final int node_num = 100; Number of virtual nodes associated with each machine node
Public Shard (list<string> shards) {
Super ();
This.shards = shards;
Init ();
}
private void Init () {//Initialize consistency hash ring
nodes = new Treemap<long, string> ();
for (int i = 0; I! = Shards.size (); ++i) {//each real machine node requires an associated virtual node
Final String shardinfo = Shards.get (i);
for (int n = 0; n < node_num; n++)
A real Machine node association node_num virtual nodes
Nodes.put (Hash ("shard-" + i + "-node-" + N), shardinfo);
}
}
public string Getshardinfo (string key) {
Sortedmap<long, string> tail = nodes.tailmap (hash (key)); Find a virtual node clockwise along the ring
if (tail.size () = = 0) {
Return Nodes.get (Nodes.firstkey ());
}
Return Tail.get (Tail.firstkey ()); Returns the information for the virtual node corresponding to the real machine node
}
/**
* MurmurHash algorithm, non-cryptographic hash algorithm, high performance,
* Compared to traditional crc32,md5,sha-1 (both algorithms are cryptographic hash algorithms, the complexity itself is very high, resulting in the performance of the damage is inevitable)
* Equal hash algorithm is much faster, and it is said that the collision rate of this algorithm is very low.
* http://murmurhash.googlepages.com/
*/
Private Long hash (String key) {
Bytebuffer buf = Bytebuffer.wrap (Key.getbytes ());
int seed = 0X1234ABCD;
Byteorder Byteorder = Buf.order ();
Buf.order (Byteorder.little_endian);
Long m = 0xc6a4a7935bd1e995l;
int r = 47;
Long h = seed ^ (buf.remaining () * m);
Long K;
while (Buf.remaining () >= 8) {
K = Buf.getlong ();
K *= m;
K ^= k >>> R;
K *= m;
H ^= K;
H *= m;
}
if (buf.remaining () > 0) {
Bytebuffer finish = bytebuffer.allocate (8). Order (
Byteorder.little_endian);
For Big-endian version, does this first:
Finish.position (8-buf.remaining ());
Finish.put (BUF). Rewind ();
H ^= Finish.getlong ();
H *= m;
}
H ^= h >>> R;
H *= m;
H ^= h >>> R;
Buf.order (Byteorder);
return h;
}
}
Public class Hash {
public static void Main (string[] args) {
& nbsp //TODO auto-generated method stub
list<string > popids = new arraylist<string> ();
popids.add ("111");
popids.add ("222");
popids.add ("333");
popids.add ("444");
popids.add ("555");
shard s = new Shard (popids);
for (int i=0;i<4;i++)
{
System.out.println (S.getshardinfo ("100000000000000001" +i));
}
}
Java Conformance Hashi transcoding