Skip to content

Commit d6dcd00

Browse files
committed
一致性hash负载均衡实现
1 parent d34e614 commit d6dcd00

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package org.hegemol.ymir.core.balance;
2+
3+
import java.util.List;
4+
import java.util.SortedMap;
5+
import java.util.TreeMap;
6+
7+
import org.hegemol.ymir.common.entity.ServiceBean;
8+
9+
/**
10+
* 一致性hash
11+
*
12+
* @author KevinClair
13+
**/
14+
public class ConsistentHashLoadBalance extends AbstractLoadBalance{
15+
16+
private static final String INSTANCE = "-INSTANCE-";
17+
18+
@Override
19+
protected ServiceBean loadMethod(final List<ServiceBean> services, final String address) {
20+
TreeMap<Long, ServiceBean> treeMap = new TreeMap<>();
21+
services.forEach(each -> {
22+
for (int i = 0; i < each.getFictitiousInstance()-1; i++) {
23+
Long hashKey = hash(each.getAddress() + INSTANCE + i);
24+
treeMap.put(hashKey, each);
25+
}
26+
});
27+
long clientHash = hash(address);
28+
SortedMap<Long, ServiceBean> sortedMap = treeMap.tailMap(clientHash);
29+
if (!sortedMap.isEmpty()) {
30+
return sortedMap.get(sortedMap.firstKey());
31+
}
32+
return treeMap.firstEntry().getValue();
33+
}
34+
}

0 commit comments

Comments
 (0)