前言
Ribbon作為Spring Cloud全家桶核心元件之一,是一套基于用戶端的軟負載工具,主要是基于Netfilx釋出的開源項目,功能主要是應用于用戶端軟體的負載均衡算法、服務之間調用的橋梁。作為用戶端的元件,提供了一系列的配置,如拒絕政策、逾時重試、服務發現政策….主要的核心元件也是基于Load Balancer,會提供一些負載均衡政策,如輪詢、權重輪詢、随機連接配接、重試等政策。
注冊中心、負載均衡、生産者服務之間的注冊與調用情況
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAnYldHL0FWby9mZvwFN4ETMfdHLkVGepZ2XtxSZ6l2clJ3LcV2Zh1Wa9M3clN2byBXLzN3btgHL9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsQTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5SN3ATN5UGOiJzN4MWMjBTNzYzXyMDNzETMwIzLcBTMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
關于ribbon是如何實作服務之間調用的,可以看我之前寫的一篇文章 Feign遠端調用原理分析 - 掘金 ,Feign基于ribbon做遠端調用
Ribbon負載均衡政策核心
IRule 接口定義了一系列的負載均衡政策
核心接口ILoadBalance定義了一系列的方法,包括擷取服務清單、選擇、添加、選擇服務。
自定義負載均衡政策
1:代碼方式配置新政策
首先定義Configuration的MyRule類,定義myRule方法傳回IRule接口。
public class CustomRule extends AbstractLoadBalancerRule {
private int total = 0; //被調用的次數
private int currentIndex = 0; //目前是誰在提供服務
public Server choose(ILoadBalancer lb, Object o) {
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) {
return null;
}
//int index = chooseRandomInt(serverCount);
//server = upList.get(index);
if (total < 5) {
server = upList.get(currentIndex);
total++;
System./out/.println(“<5” + total + “:” + currentIndex);
} else {
total = 0;
currentIndex++;
if (currentIndex > upList.size() - 1) {
currentIndex = 0;
System./out/.println(“>size” + total + “:” + currentIndex);
}
server = upList.get(currentIndex);
System./out/.println(“>5” + total + “:” + currentIndex);
}
if (server == null) {
Thread./yield/();
continue;
}
if (server.isAlive()) {
return (server);
}
server = null;
Thread./yield/();
}
return server;
}
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
@Override
public Server choose(Object o) {
return choose(getLoadBalancer(), o);
}
}
自定義政策類CustomRule繼承AbstractLoadBalancerRule父類,重寫choose 方法,去選擇自已寫的負載均衡政策,這裡我定義的政策是一個消費者服務被調用5次後就去調下一個服務。
2:配置檔案的方式:
XXXservice: ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer. MyRule /# 負載均衡規則/
啟動類配置,需要通過自定義RestTemplate模版實作自定義政策的調用
通過postman去調服務的接口