1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| public static void main(String[] args) { List<Server> serverList = new ArrayList<>(); serverList.add(new Server(1,"服务器1","8080","127.0.0.1",90,0,0,"",2000)); serverList.add(new Server(2,"服务器2","8090","127.0.0.2",80,0,0,"",3000)); serverList.add(new Server(3,"服务器3","8088","127.0.0.3",70,0,0,"",3000)); serverList.add(new Server(4,"服务器4","8099","127.0.0.4",70,0,0,"",3000)); serverList.add(new Server(5,"服务器5","8070","127.0.0.5",80,0,0,"",3000)); serverList.add(new Server(6,"服务器6","8060","127.0.0.6",70,0,0,"",4000)); serverList.add(new Server(7,"服务器7","8050","127.0.0.7",80,0,0,"",5000));
AdaptiveLoadBalance adaptiveLoadBalance = new AdaptiveLoadBalance();
Invocation invocation = new Invocation(); for (int i = 0; i < 1000; i++) { System.out.println(adaptiveLoadBalance.doSelect(serverList,invocation).toString()); } Iterator iterator = adaptiveLoadBalance.adaptiveMetrics.metricsStatistics.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<String, AdaptiveMetrics> entry = (Map.Entry<String, AdaptiveMetrics>) iterator.next(); System.out.println("Key: "+entry.getKey()+" consumerReq: "+entry.getValue().consumerReq ); } }
private Server selectByP2C(List<Server> invokers, Invocation invocation){ int length = invokers.size(); if(length == 1) { return invokers.get(0); }
if(length == 2) { return chooseLowLoadInvoker(invokers.get(0),invokers.get(1),invocation); } int pos1 = ThreadLocalRandom.current().nextInt(length); int pos2 = ThreadLocalRandom.current().nextInt(length - 1); if (pos2 >= pos1) { pos2 = pos2 + 1; } return chooseLowLoadInvoker(invokers.get(pos1),invokers.get(pos2),invocation); }
private Server chooseLowLoadInvoker(Server invoker1,Server invoker2,Invocation invocation){ int weight1 = invoker1.getWeight(); int weight2 = invoker2.getWeight(); int timeout1 = getTimeout(invoker1, invocation); int timeout2 = getTimeout(invoker2, invocation); long load1 = Double.doubleToLongBits(adaptiveMetrics.getLoad(getServiceKey(invoker1,invocation),weight1,timeout1 )); long load2 = Double.doubleToLongBits(adaptiveMetrics.getLoad(getServiceKey(invoker2,invocation),weight2,timeout2 ));
if (load1 == load2) { int totalWeight = weight1 + weight2; if (totalWeight > 0) { int offset = ThreadLocalRandom.current().nextInt(totalWeight); if (offset < weight1) { return invoker1; } return invoker2; } return ThreadLocalRandom.current().nextInt(2) == 0 ? invoker1 : invoker2; } return load1 > load2 ? invoker2 : invoker1; }
|