美文网首页
Ribbon自定义负载均衡轮询算法

Ribbon自定义负载均衡轮询算法

作者: CodeYang | 来源:发表于2021-08-27 11:11 被阅读0次

一、首先注释 @LoadBalanced 默认的负载均衡算法,使用我们自己的

image.png

二、定义我们自己的 LoadBalancer

image.png
  1. 接口
public interface LoadBalancer {
    ServiceInstance instances(List<ServiceInstance> serviceInstanceList);
}
  1. 实现类
/**
 * 手写轮询算法
 */
@Component
public class MyLoadBalancer implements LoadBalancer{


    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private final int getAndIncrement(){
        int current;
        int next;
        do {
            current=this.atomicInteger.get();
            next = current >= 2147483647 ? 0 :current + 1;   //int 最大值 2147483647
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("*******第几次访问呢,次数next:"+next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstanceList) {
        int index=getAndIncrement() % serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }
}

三、 controller 调用

    @Resource
    RestTemplate restTemplate;
  @Resource
    LoadBalancer loadBalancer;

    /**
     * 使用自定义的轮询算法
     * @return
     */
    @GetMapping(value = "/consumer/lb")
    public String getLoadBalancerLb(){
        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PROVIDER");
        if(instanceList == null || instanceList.size()<=0){
            return null;
        }
        ServiceInstance instances = loadBalancer.instances(instanceList);
        URI uri = instances.getUri();
        return restTemplate.getForObject(uri+"/provider/hello/自定义轮询",String.class);
    }

四、测试调用,测试成功

第一次调用.png 第二次调用.png

相关文章

网友评论

      本文标题:Ribbon自定义负载均衡轮询算法

      本文链接:https://www.haomeiwen.com/subject/esiciltx.html