ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
轮询策略的算法如下: ``` 实际调用的服务器下标(Z)=同一接口的总请求数(Y) % 集群服务器总数(X) ``` 比如 8001服务端、8002服务端组成的集群有 2 台机器,则如下进行轮询: ``` 同一接口总请求数1 Z=1 % 2 = 1,调用8001服务; 同一接口总请求数2 Z=2 % 2 = 0,调用8002服务; 同一接口总请求数3 Z=3 % 2 = 1,调用8001服务; 同一接口总请求数4 Z=4 % 2 = 0,调用8002服务; ...如此类推... ``` <br/> Ribbon实现轮询策略可以采用两种方法实现: **1. 直接在`RestTemplate`组件上标注注解`@LoadBalanced`。** ```java @Configuration public class ApplicationContextConfig { @Bean @LoadBalanced //该注解默认的负载均衡策略是轮询策略 public RestTemplate getRestTemplate() { return new RestTemplate(); } } ``` **2. 实现接口`LoadBalaner`来实现轮询策略。** 步骤如下: (1)实现接口`LoadBalaner`。 ```java /** * 如果实现接口LoadBalaner,则不要使用注解@LoadBalanced */ @Component public class MyLoadBalaner implements LoadBalaner { private AtomicInteger atomicInteger = new AtomicInteger(0); public final int getIncrement() { int current; int next; do { //首次初始化current为 1 current = this.atomicInteger.get(); next = current >= 2147483647 ? 0 : current + 1; //compareAndSet方法判断两个参数值相等则返回true,否则返回false } while (!this.atomicInteger.compareAndSet(current, next)); System.out.print("总请求次数:" + next + " "); return next; } @Override public ServiceInstance instance(List<ServiceInstance> instances) { //实际调用的服务器下标(Z)=同一接口的总请求数(Y) % 集群服务器总数(X) int index = getIncrement() % instances.size(); return instances.get(index); } } ``` (2)调用该接口来访问服务。 ```java @RestController @RequestMapping("/order") public class OrderController { @Value("${provider.payment.name}") private String PROVIDER_PAYMENT_NAME; @Resource private LoadBalaner loadBalaner; @GetMapping("/lb") public String getPaymentLB() { List<ServiceInstance> instances = discoveryClient.getInstances(PROVIDER_PAYMENT_NAME); if (instances == null || instances.size() == 0) { return null; } ServiceInstance serviceInstance = loadBalaner.instance(instances); URI uri = serviceInstance.getUri(); System.out.println(uri + "/payment/lb"); return restTemplate.getForObject(uri + "/payment/lb", String.class); } } ``` (3)刷新地址 6 次,控制台输出如下。 ```java 总请求次数:1 http://192.168.56.1:8002/payment/lb 总请求次数:2 http://192.168.56.1:8001/payment/lb 总请求次数:3 http://192.168.56.1:8002/payment/lb 总请求次数:4 http://192.168.56.1:8001/payment/lb 总请求次数:5 http://192.168.56.1:8002/payment/lb 总请求次数:6 http://192.168.56.1:8001/payment/lb ```