package demo;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* User: ldj
* Date: 2024/5/28
* Time: 5:58
* Description: 哈希环算法
*/
public class HashLoop {
public static void main(String[] args) {
//记录机器的状态
List<Integer> indexList = new ArrayList<>();
indexList.add(0);
indexList.add(null);
indexList.add(2);
int index = getIndex(indexList);
System.out.println(index);
}
//code: 环的位移点,这里将360度环等分12份 index:是机器的编号0,1,2
public static int getIndex(List<Integer> indexList) {
String str = UUID.randomUUID().toString().replaceAll("-", "");
int num = Math.abs(str.hashCode() % 361);
System.out.println(num);
if (num <= 30 && indexList.get(0) != null) {
return 0;
}
if (num <= 60 && indexList.get(1) != null) {
return 1;
}
if (num <= 90 && indexList.get(2) != null) {
return 2;
}
if (num <= 120 && indexList.get(0) != null) {
return 0;
}
if (num <= 150 && indexList.get(1) != null) {
return 1;
}
if (num <= 180 && indexList.get(2) != null) {
return 2;
}
if (num <= 210 && indexList.get(0) != null) {
return 0;
}
if (num <= 240 && indexList.get(1) != null) {
return 1;
}
if (num <= 270 && indexList.get(2) != null) {
return 2;
}
if (num <= 300 && indexList.get(0) != null) {
return 0;
}
if (num <= 330 && indexList.get(1) != null) {
return 1;
}
if (indexList.get(2) != null) {
return 2;
}
throw new RuntimeException("错误!找不到运行正常的机器");
}
}
哈希环负载均衡
于 2024-05-28 07:25:48 首次发布