File tree 1 file changed +34
-0
lines changed
src/main/java/org/hegemol/ymir/core/balance
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments