简介
Ribbon是Netflix发布的负载均衡器,它有助于控制HTTP和TCP的客户端的行为。为Ribbon配置服务提供者地址后,Ribbon就可基于某种负载均衡算法,自动地帮助服务消费者去请求。Ribbon默认为我们提供了很多负载均衡算法,例如轮询、随机等。当然,我们也可为Ribbon实现自定义的负载均衡算法。
在Spring Cloud中,当Ribbon与Eureka配合使用时,Ribbon可自动从Eureka Server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例。
负载均衡算法
IRule是以下七种负载均衡算法的父接口
替换负载均衡算法
所谓的自定义Ribbon Client的主要作用就是替代Ribbon默认的负载均衡策略,注意:自定义的Ribbon Client是有针对性的,一般一个自定义的Ribbon Client是对一个服务提供者(包括服务名相同的一系列副本)而言的。自定义了一个Ribbon Client 它所设定的负载均衡策略只对某一特定服务名的服务提供者有效,但不能影响服务消费者与别的服务提供者通信所使用的策略。根据官方文档的意思,推荐在 springboot 主程序扫描的包范围之外进行自定义配置类。
如果要自定义Ribbon配置, 则需要把这个配置类放在@SpringBootApplication扫不到的包中(@ComponentScan),因为如果可以扫到自定义的Ribbon配置类的话,那么会对所有的Riboon都生效,也就是说这种情况下所有的微服务的负载均衡算法都是相同的。配置类不应该在SpringBoot的包路径下,而是通过@RibbonClient 注解加载:
该类不在@ComponentScan扫描的包下
@Configuration
public class RuleConfiguration {
@Bean
public IRule getRule(){
return new RandomRule();
}
}
启动类添加注解
@RibbonClient(name = "PAYMENT-SERVICE",configuration = RuleConfiguration.class)
访问消费者,负载均衡模式成功切换到随机。
使用自定义负载均衡算法
自定义的轮询算法类
@Component
@Slf4j
public class MyLoadBalancer implements MyILoadBalancer {
private AtomicInteger atomicInteger=new AtomicInteger(0);
private final static String SERVICE_NAME="Payment-Service";
@Autowired
private DiscoveryClient discoveryClient;
private ServiceInstance getServiceInstance() {
List<ServiceInstance> instances = discoveryClient.getInstances(SERVICE_NAME);
System.out.println(instances);;
if(instances.isEmpty()||instances==null){
return null;
}
else {
int current;
int next=0;
do{
current = atomicInteger.get();
next = current > Integer.MAX_VALUE ? 0 : current + 1;
}while (!this.atomicInteger.compareAndSet(current,next));
return instances.get(next%instances.size());
}
}
@Override
public URI getURI() {
return getServiceInstance().getUri();
}
}
Controller中调用的方法
@GetMapping("/lb/test")
public String testLB(){
return restTemplate.getForObject(myILoadBalancer.getURI()+"/loadbanlance/test/provider",String.class);
}