天天看點

SpringCloud - Ribbon 用戶端負載均衡工具

1. Ribbon是什麼?

SpringCloud - Ribbon 用戶端負載均衡工具

多個“微服務提供者”在eureka叢集裡注冊服務,然後消費者要調用服務時,通過ribbon從eureka叢集裡查詢到可用的服務清單(分别有8001,8002,8003)

然後根據ribbon的load balance算法,選擇一個進行調用

SpringCloud - Ribbon 用戶端負載均衡工具

2. Ribbon能幹嘛?

SpringCloud - Ribbon 用戶端負載均衡工具

3. 在用戶端內建Ribbon, Eureka

為啥需要eureka包,上節說了ribbon內建在用戶端,用戶端需要從注冊中心擷取哪些位址可用。是以需要eureka。

SpringCloud - Ribbon 用戶端負載均衡工具

在主配置檔案application.yml中,做eureka配置:

SpringCloud - Ribbon 用戶端負載均衡工具

 在主程式開啟eureka:

SpringCloud - Ribbon 用戶端負載均衡工具

由于用戶端的所有請求都是通過RestTemplate (SpringCloud - RestTempleate使用)這個bean來通路微服務的,是以隻要在這裡加上@LoadBalanced即可。

SpringCloud - Ribbon 用戶端負載均衡工具

重點:

SpringCloud - Ribbon 用戶端負載均衡工具
SpringCloud - Ribbon 用戶端負載均衡工具

4. Ribbon的負載均衡算法

所有的負載均衡算法,都是如下的繼承鍊:

預設的負載均衡算法是:輪訓,8001, 8002, 8003輪着來

SpringCloud - Ribbon 用戶端負載均衡工具
SpringCloud - Ribbon 用戶端負載均衡工具
SpringCloud - Ribbon 用戶端負載均衡工具

不用預設的“輪詢”,改用其他算法時要注意(官方建議):不要把LB算法的java config檔案放在與@SpringBootApplcation主函數相同的目錄(包括其子目錄)下面,以避免@ComponetScan直接把LB算法的java config檔案掃描進入,使得所有的@RibbonClients共享。

應該讓每個@RibbonClients自己選擇用什麼LB算法。

SpringCloud - Ribbon 用戶端負載均衡工具

LB算法的java config檔案:

SpringCloud - Ribbon 用戶端負載均衡工具

@SpringBootApplication函數顯示注解@RibbonClient:

SpringCloud - Ribbon 用戶端負載均衡工具

重寫方法即可