看到一個哥們寫的一個簡單的工具類感覺挺好玩的:
負載均衡有很多種方法,權重呀,隨機,輪詢等等;
實現一個最簡單的,那就是隨機和輪詢,輪詢有個注意的就是,在多線程情況下也是ok的:
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 負載均衡工具類
*/
public class LoadBalancerUtil {
private final static Random rand = new Random();
private final static AtomicInteger nextCyclicCounter = new AtomicInteger(0);
/**
* 隨機算法
*
* @param number 隨機數的上線
* @return 返回 0 ~ (number-1) 的隨機數
*/
public static int randomRule(int number) {
return rand.nextInt(number);
}
/**
* 輪巡算法
*
* @param modulo 取餘的闊值
* @return 當前輪巡的數值 0 ~ (number-1)
*/
public static int roundRule(int modulo) {
int current;
int next;
do {
current = nextCyclicCounter.get();
next = (current + 1) % modulo;
} while (!nextCyclicCounter.compareAndSet(current, next));
return next;
}
public static void main(String[] args) {
// for (int i = 0; i < 1000; i++) {
// System.out.println(randomRule(3));
// }
// System.out.println("===============================");
// for (int i = 0; i < 1000; i++) {
// System.out.println(roundRule(3));
// }
for (int i = 0; i < 10; i++) {
CompletableFuture.runAsync(() -> {
while (true) {
System.out.println(roundRule(50));
}
});
}
try {
TimeUnit.SECONDS.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}