16
16
*/
17
17
package org .apache .seata .discovery .loadbalance ;
18
18
19
+ import java .nio .charset .StandardCharsets ;
19
20
import java .security .MessageDigest ;
20
21
import java .security .NoSuchAlgorithmException ;
21
22
import java .util .List ;
29
30
30
31
/**
31
32
* The type consistent hash load balance.
32
- *
33
33
*/
34
34
@ LoadLevel (name = LoadBalanceFactory .CONSISTENT_HASH_LOAD_BALANCE )
35
35
public class ConsistentHashLoadBalance implements LoadBalance {
36
36
37
37
/**
38
38
* The constant LOAD_BALANCE_CONSISTENT_HASH_VIRTUAL_NODES.
39
39
*/
40
- public static final String LOAD_BALANCE_CONSISTENT_HASH_VIRTUAL_NODES = LoadBalanceFactory .LOAD_BALANCE_PREFIX + "virtualNodes" ;
40
+ public static final String LOAD_BALANCE_CONSISTENT_HASH_VIRTUAL_NODES = LoadBalanceFactory .LOAD_BALANCE_PREFIX
41
+ + "virtualNodes" ;
41
42
/**
42
43
* The constant VIRTUAL_NODES_NUM.
43
44
*/
44
- private static final int VIRTUAL_NODES_NUM = ConfigurationFactory .getInstance ().getInt (LOAD_BALANCE_CONSISTENT_HASH_VIRTUAL_NODES , VIRTUAL_NODES_DEFAULT );
45
+ private static final int VIRTUAL_NODES_NUM = ConfigurationFactory .getInstance ().getInt (
46
+ LOAD_BALANCE_CONSISTENT_HASH_VIRTUAL_NODES , VIRTUAL_NODES_DEFAULT );
45
47
46
48
@ Override
47
49
public <T > T select (List <T > invokers , String xid ) {
@@ -51,7 +53,7 @@ public <T> T select(List<T> invokers, String xid) {
51
53
private static final class ConsistentHashSelector <T > {
52
54
53
55
private final SortedMap <Long , T > virtualInvokers = new TreeMap <>();
54
- private final HashFunction hashFunction = new MD5Hash ();
56
+ private final HashFunction hashFunction = new SHA256Hash ();
55
57
56
58
ConsistentHashSelector (List <T > invokers , int virtualNodes ) {
57
59
for (T invoker : invokers ) {
@@ -68,12 +70,12 @@ public T select(String objectKey) {
68
70
}
69
71
}
70
72
71
- @ SuppressWarnings ("lgtm[java/weak-cryptographic-algorithm]" )
72
- private static class MD5Hash implements HashFunction {
73
+ private static class SHA256Hash implements HashFunction {
73
74
MessageDigest instance ;
74
- public MD5Hash () {
75
+
76
+ public SHA256Hash () {
75
77
try {
76
- instance = MessageDigest .getInstance ("MD5 " );
78
+ instance = MessageDigest .getInstance ("SHA-256 " );
77
79
} catch (NoSuchAlgorithmException e ) {
78
80
throw new IllegalStateException (e .getMessage (), e );
79
81
}
@@ -83,13 +85,13 @@ public MD5Hash() {
83
85
public long hash (String key ) {
84
86
instance .reset ();
85
87
instance .update (key .getBytes ());
86
- byte [] digest = instance .digest ();
87
- long h = 0 ;
88
- for (int i = 0 ; i < 4 ; i ++) {
89
- h <<= 8 ;
90
- h |= (( int ) digest [i ]) & 0xFF ;
88
+ byte [] digest = instance .digest (key . getBytes ( StandardCharsets . UTF_8 ) );
89
+ long hash = 0 ;
90
+ for (int i = 0 ; i < 8 && i < digest . length ; i ++) {
91
+ hash <<= 8 ;
92
+ hash |= digest [i ] & 0xff ;
91
93
}
92
- return h ;
94
+ return hash ;
93
95
}
94
96
}
95
97
0 commit comments