Ribbon 结合 Resttemplate自定义负载均衡算法

public interface LoadBalance {

    //获取Eureka的服务总数
    ServiceInstance instances(List<ServiceInstance> serviceInstances);

}
@Service(value = "loadBalance")
public class MyLb implements LoadBalance {

  private AtomicInteger atomicInteger = new AtomicInteger(0);

  // 自增加组件 适用于高并发
  public final int getAndIncrement() {
    int current;
    int next;
    do {
      current = this.atomicInteger.get();
      next = current >= 2147483647 ? 0 : current + 1;
    } while (!this.atomicInteger.compareAndSet(current, next));
    System.out.println("********自增到哪个数字-》 next" + next);
    return next;
  }

  @Override
  public ServiceInstance instances(List<ServiceInstance> serviceInstances) {

    int index = getAndIncrement() % serviceInstances.size();
    return serviceInstances.get(index);

  }
}
  @GetMapping(value = "/customer/payment/lb")
  public String getPaymentLB() {
    List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
    if (instances == null || instances.size() <= 0) {
      return null;
    }

    ServiceInstance serviceInstance = loadBalance.instances(instances);
    URI uri = serviceInstance.getUri();

    return restTemplate.getForObject(uri + "/payment/lb", String.class);
  }
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页