美文网首页
手写Ribbon轮询算法

手写Ribbon轮询算法

作者: 吃货_ee62 | 来源:发表于2021-09-13 15:08 被阅读0次

个人学习笔记

原理+JUC(CAS+自旋锁的复习)

Ribbon负载均衡的轮询算法:

rest接口第几次请求数%服务器集群总数量=实际调用服务器位置下标,每次服务重启后rest接口计数从1开始。

1.ApplicationContextBean去掉注解@LoadBalanced


image.png

2.LoadBalancer接口

package com.gods.springcloud.lb.impl;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

public interface LoadBalancer {

    ServiceInstance instance(List<ServiceInstance> serviceInstances);
}

3.MyLB

package com.gods.springcloud.lb;


import com.gods.springcloud.lb.impl.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component

public class MyLB  implements LoadBalancer {
    //AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减。
    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 instance(List<ServiceInstance> serviceInstances) {
        int next = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(next);
    }
}

4.OrderController

 @Resource
    private LoadBalancer loadBalancer;
    @Resource
    private DiscoveryClient discoveryClient;

  @GetMapping("/consumer/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances==null || instances.size()<=0){
            return null;
        }
        ServiceInstance serviceInstance=loadBalancer.instance(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }

5.测试

http://localhost/consumer/payment/lb

image.png

相关文章

网友评论

      本文标题:手写Ribbon轮询算法

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