ribbon(依然有人使用,还是很难替换掉) 负载均衡 + restTemplate实现rpc远程调用
新版eureka依赖集成好了ribbon,可以不用重新导入
consumer远程调用provider使用到了一个resttemplate类 在消费者端的consumer中调用
@Resource
private RestTemplate restTemplate;
// 手写轮询算法 轮询算法核心代码行为取模运算获取需要调用的服务器的具体实例
@Component
public class MyBalanceRule implements LoadBalance {
// 用来计数接口调用次数的计数器
private AtomicInteger counter = new AtomicInteger(0);
// counter的最大长度
private final int MAX_LENGTH = Integer.MAX_VALUE;
// 获取并
public final int getAndIncrement() {
int current = 0;
int next = 0;
do{
current = counter.get();
next = (current > MAX_LENGTH) ? 0 : current + 1;
} while (!this.counter.compareAndSet(current,next));
System.out.println("服务器选举次数 : " + next);
return next;
}
@Override
public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstances) {
int index = getAndIncrement();
int size = serviceInstances.size();
if(size == 0){
System.out.println("没有服务器");
return null;
}
return serviceInstances.get(index);
}
}
轮询的使用
@Resource
private LoadBalance loadBalance;
@GetMapping(value = "consumer/payment/lb")
public String getPaymentLb(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
int size = instances.size();
if(size <= 0){
return "没有服务注册到服务中心,请先注册服务...";
}
ServiceInstance currInstance = loadBalance.getServiceInstance(instances);
URI uri = currInstance.getUri();
return restTemplate.getForObject(uri + "/payment/lb",String.class);
}
标签:int,springcloud,轮询,next,current,ribbon,size
From: https://www.cnblogs.com/huoziqi/p/17533367.html