1 简介
Netflix Ribbon是Netflix开源的客户端负载均衡组件,主要功能是提供客户端的软件负载均衡算法
和服务调用
。在Spring Cloud Load Balancer出现之前,它是Spring Cloud生态里唯一的负载均衡组件。目前市场上绝大多数的Spring Cloud应用还是使用Ribbon作为其负载均衡组件。
Spring Netflix全家桶都已经进入维护模式,不再增加新特性。
总之一句话: Ribbon 就是 负载均衡
+ RestTemplate
调用,最终实现RPC的远程调用。
2 负载均衡和Rest调用
Ribbon 是一个软负载均衡的客户端组件,它可以和其他所需请求的客户端结合使用,和 eureka 结合只是其中的一个实例。
架构说明:
Ribbon 在工作时分成两步:
第一步:先选择 EurekaServer,它优先选择在同一个区域内负载较少的server
第二步:再根据用户指定的策略,在从server 取到的服务注册列表中选择一个地址
其中Ribbon 提供了多种策略:比如轮询
、随机
和根据响应时间加权
新版eureka引入了ribbon,所以不用自己引入也可以使用负载均衡,最新版已经去掉了Ribbon采用spring-cloud-starter-loadbalancer
getForObject 方法 / getForEntity方法
@GetMapping("/payment/getForEnity")
public CommonResult getPayment2(@PathVariable long id){
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get?id="+id,CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}
return new CommonResult(444,"操作失败",null);
}
postForObject 方法 / postForEntity 方法
3 Ribbon的负载均衡算法
IRule:
根据特定算法从服务列表中选取一个要访问的服务
com.netflix.loadbalancer.RoundRobinRule
轮询
com.netflix.loadbalancer.RandomRule
随机
com.netflix.loadbalancer.RetryRule
先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务
WeightedResponseTimeRule
对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择
BestAvailableRule
会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
AvailabilityFilteringRule
先过滤掉故障实例,再选择并发较小的实例
ZoneAvoidanceRule
默认规则,复合判断server所在区域的性能和server的可用性选择服务器
4 负载均衡算法规则的替换
这个自定义配置类不能放在 @ComponentScan 所扫描的当前包下以及子包下,否则自定义的配置类就会被所有的 Ribbon 客户端所共享,达不到特殊化定制的目的了。
package com.micah.rule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author m.kong
* @Date 2021/4/20 下午6:28
* @Version 1
* @Description 自定义负载均衡规则类
*/
@Configuration
public class MyRule {
@Bean
public IRule myRule(){
return new RandomRule();
}
}
主启动类上加@RibbonClient注解
package com.micah.customer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
/**
* @Author m.kong
* @Date 2021/3/31 下午5:04
* @Version 1
* @Description
*/
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MyRule.class)
public class CustomerApplication {
public static void main(String[] args) {
SpringApplication.run(CustomerApplication.class,args);
}
}
测试:
5 手写负载均衡算法
负载均衡算法: 轮询
rest 接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标
每次服务器重启后rest接口数从1开始
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-SERVICE")
如:
List[0] instances = 127.0.0.1:8002
List[1] instances = 127.0.0.1:8001
8001 + 8002 组合成为集群,它们共计2台机器,集群总数为2,按照轮询算法原理:
源码:
//IRule接口
public interface IRule{
/*
* choose one alive server from lb.allServers or
* lb.upServers according to key
*
* @return choosen Server object. NULL is returned if none
* server is available
*/
//选择哪个服务实例
public Server choose(Object key);
public void setLoadBalancer(ILoadBalancer lb);
public ILoadBalancer getLoadBalancer();
}
public class RoundRobinRule extends AbstractLoadBalancerRule {
private AtomicInteger nextServerCyclicCounter;
private static final boolean AVAILABLE_ONLY_SERVERS = true;
private static final boolean ALL_SERVERS = false;
private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);
public RoundRobinRule() {
nextServerCyclicCounter = new AtomicInteger(0);
}
public RoundRobinRule(ILoadBalancer lb) {
this();
setLoadBalancer(lb);
}
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
}
Server server = null;
int count = 0;
while (server == null && count++ < 10) {
List<Server> reachableServers = lb.getReachableServers();
List<Server> allServers = lb.getAllServers();
int upCount = reachableServers.size();
int serverCount = allServers.size();
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
int nextServerIndex = incrementAndGetModulo(serverCount);
server = allServers.get(nextServerIndex);
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
// Next.
server = null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
/**
* Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
*
* @param modulo The modulo to bound the value of the counter.
* @return The next value.
*/
private int incrementAndGetModulo(int modulo) {
for (;;) {
int current = nextServerCyclicCounter.get();
int next = (current + 1) % modulo;
if (nextServerCyclicCounter.compareAndSet(current, next))
return next;
}
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}