04.3 Ribbon核心组件IRule和自定义规则

1. Ribbon负载均衡算法

  • RoundRobinRule

    轮询算法,所有注册中心中的provider会按顺序访问

  • RandomRule

    随机算法,随机访问注册中心中的provider

  • AvailabilityFilteringRule

    会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,还有并发的连接数量超过阈值的服务,然后对剩余的服务列表按照轮询策略进行访问

  • WeightedResponseTimeRule

    根据平均响应时间计算所有服务的权重,响应时间越快服务权重越大被选中的概率越高。刚启动时如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够,会切换到WeightedResponseTimeRule

  • RetryRule

    先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务

  • BestAvailableRule

    会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务

  • ZoneAvoidanceRule

    默认规则,复合判断server所在区域的性能和server的可用性选择服务器

2. 自定义负载均衡算法

2.1 修改microservicecloud-consumer-dept-80

新建package com.atguigu.myrule,并新建自定义Robbin规则类 MySelfRule

官方文档明确给出了警告:
这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,
否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,也就是说
我们达不到特殊化定制的目的了。

1
2
3
4
5
6
7
8
@Configuration
public class MySelfRule {
@Bean
public IRule myRule() {
// return new RandomRule(); //Ribbon默认是轮询,我自定义为随机
return new NewRandomRule();
}
}

2.2 修改主启动类

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name="MICROSERVICECLOUD-DEPT", configuration= MySelfRule.class)
public class ConsumerDept80Application {
public static void main(String[] args) {
SpringApplication.run(ConsumerDept80Application.class, args);
}
}

2.3 自定义规则

轮询策略基础上,每个服务器要求被调用5次。也即以前是每台机器一次,现在是每台机器5次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class NewRandomRule extends AbstractLoadBalancerRule {
private int total = 0; //总共被调用的次数,目前要求每台被调用5次
private int currentIndex = 0;//当前提供服务的机器号
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
}
Server server = null;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
List<Server> upList = lb.getReachableServers();
List<Server> allList = lb.getAllServers();
int serverCount = allList.size();
if (serverCount == 0) {
/*
* No servers. End regardless of pass, because subsequent passes
* only get more restrictive.
*/
return null;
}
// int index = rand.nextInt(serverCount);
// server = upList.get(index);
if (total < 5) {
server = upList.get(currentIndex);
total++;
} else {
total = 0;
currentIndex++;
if (currentIndex >= upList.size()) {
currentIndex = 0;
}

}
if (server == null) {
/*
* The only time this should happen is if the server list were
* somehow trimmed. This is a transient condition. Retry after
* yielding.
*/
Thread.yield();
continue;
}
if (server.isAlive()) {
return (server);
}
// Shouldn't actually happen.. but must be transient or a bug.
server = null;
Thread.yield();
}
return server;
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}

2.4 效果演示

资源获取

公众号回复 : Ribbon核心组件IRule和自定义规则 获取本节代码

公众号回复 : SpringCloud思维导图

Tips

欢迎收藏和转发,感谢你的支持!(๑•̀ㅂ•́)و✧

欢迎关注我:后端小哥,专注后端开发,希望和你一起进步!