负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标 ,每次服务重启动后rest接口计数从1开始。 List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE"); 如: List [0] instances = 127.0.0.1:8002 List [1] instances = 127.0.0.1:8001 8001 8002 组合成为集群,它们共计2台机器,集群总数为2, 按照轮询算法原理: 当总请求数为1时: 1 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001 当总请求数位2时: 2 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002 当总请求数位3时: 3 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001 当总请求数位4时: 4 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002 如此类推......
写一个本地负载均衡器
设现在有俩个服务端口8001 8002幼由80端口调动
其中8001 8002 的controller中
代码语言:javascript复制@GetMapping(value = "/payment/lb")
public String getPaymentLB()
{
return serverPort;
}
80 的一个接口为:
代码语言:javascript复制public interface LoadBalancer
{
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
实现类
代码语言:javascript复制@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: " next);
return next;
}
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances)
{
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
调用 方法
代码语言:javascript复制 @Resource
private RestTemplate restTemplate;
//可以获取注册中心上的服务列表
@Resource
private DiscoveryClient discoveryClient;
@Resource
private LoadBalancer loadBalancer;
@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.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri "/payment/lb",String.class);
}
ApplicationContextBean去掉注解@LoadBalanced