In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces how the java implementation of the consistent hash algorithm is, the content is very detailed, interested friends can refer to it, I hope it can be helpful to you.
Today we use java to implement the consistent hash algorithm, focusing on two aspects: consistency and virtual nodes.
Cut the crap and go straight to the code:
Public class ConsistencyHash {
Private TreeMap nodes = null
Private List shards = new ArrayList ()
Private int VIRTUAL_NUM = 4
Public void init () {
Shards.add ("10.10.0.0-Server 0")
Shards.add ("10.10.0.1-Server 1")
Shards.add ("10.10.0.2-Server 2")
Shards.add ("10.10.0.3-Server 3")
Shards.add ("10.10.0.4-Server 4")
Nodes = new TreeMap ()
For (int I = 0; I < shards.size (); iTunes +) {
String shardInfo = shards.get (I)
For (int j = 0; j < VIRTUAL_NUM; jacks +) {
Byte [] md5Value = computeMd5 ("SHARD-" + I + "- NODE-" + j)
Long hashCode = hash (md5Value, j)
System.out.println (hashCode)
Nodes.put (hashCode, shardInfo)
}
}
Iterator iter = nodes.keySet () .iterator ()
While (iter.hasNext ()) {
Long key = iter.next ()
String obj = (String) nodes.get (key)
System.out.println (String.valueOf (key) + ":" + obj)
}
}
Public Object getShardInfo (long hash) {
Long key = hash
SortedMap tailMap = nodes.tailMap (key)
If (tailMap.isEmpty ()) {
Key = nodes.firstKey ()
} else {
Key = tailMap.firstKey ()
}
Return nodes.get (key)
}
Public void printMap () {
System.out.println (nodes)
}
Public long hash (byte [] digest, int nTime) {
Long rv = (long) (digest [3 + nTime * 4] & 0xFF)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.