springcloud笔记二手写简单ribbon负载均衡算法
Posted 今夜月色很美
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springcloud笔记二手写简单ribbon负载均衡算法相关的知识,希望对你有一定的参考价值。
定义LoadBalancer负载均衡接口
package com.fox.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> instances);
}
定义负载均衡实现类
package com.fox.springcloud.lb.impl;
import com.fox.springcloud.lb.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 LoadBalancerImpl implements LoadBalancer {
private AtomicInteger atomicInteger = new AtomicInteger(0);
private final int getAndIncrement(int count){
for (;;){
int current = atomicInteger.get();
int next = (current + 1) % count;
if (atomicInteger.compareAndSet(current, next)){
return next;
}
}
}
@Override
public ServiceInstance instances(List<ServiceInstance> instances) {
int index = getAndIncrement(instances.size());
return instances.get(index);
}
}
消费端使用自定义负载均衡方法
@Resource
private DiscoveryClient discoveryClient;
@Resource
private LoadBalancer loadBalancer;
@GetMapping("/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances = discoveryClient.getInstances("PAYMENT-SERVICE");
if (instances == null || instances.size() == 0){
return null;
} else {
ServiceInstance instance = loadBalancer.instances(instances);
URI uri = instance.getUri();
return restTemplate.getForObject(uri + "/payment/lb", String.class);
}
}
以上是关于springcloud笔记二手写简单ribbon负载均衡算法的主要内容,如果未能解决你的问题,请参考以下文章
springcloud学习笔记:Ribbon:负载均衡(基于客户端)
SpringCloud第二季之zookeeper,Consul和Ribbon等学习笔记