负载均衡算法
Posted nineberg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了负载均衡算法相关的知识,希望对你有一定的参考价值。
负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标 , 每次服务重启动后rest 接口计数从1开始
@Component
public class MyLB implements LoadBalancer {
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 +" 次访问*******");
//代表第几次访问
return next;
}
//负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标 , 每次服务重启动后rest 接口计数从1开始
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstance) {
// serviceInstance.size 获取集群总数
int index = getAndIncrement() % serviceInstance.size();
return serviceInstance.get(index);
}
}
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstance);
}
@Resource
private LoadBalancer loadBalancer;
@GetMapping(value = "/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.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/payment/lb",String.class);
}
以上是关于负载均衡算法的主要内容,如果未能解决你的问题,请参考以下文章