Spring Cloud Ribbon:負載均衡
Spring Cloud Ribbon是基於Netflix Ribbon實現的一套客戶端負載均衡的工具。它是一個基於HTTP和TCP的客戶端負載均衡器,它可以通過在客戶端中配置ribbonServerList來設置服務端列表去輪詢訪問以達到均衡負載的作用。
開發環境 | 版本 |
---|---|
IDEA | 2018.2.6 |
JDK | 1.8 |
Spring Boot | 2.1.0 |
Spring Cloud | Greenwich.M1 |
修改代碼和配置
在IDEA的Run/Debug Configurations中,拷貝一份當前的運行配置,並將副本爲VM options設置爲-DServer.port=8082,爲了區別不同實例接口的返回結果,新增IPConfig類:
@Component
public class IPConfig implements ApplicationListener<WebServerInitializedEvent> {
private int serverPort;
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
this.serverPort = event.getWebServer().getPort();
}
public int getPort() {
return this.serverPort;
}
}
修改provider的HelloController代碼:
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private IPConfig ipConfig;
@GetMapping("/chung")
public String helloChung(){
return "Hello Chung By Provider on :" + ipConfig.getPort();
}
}
運行兩個provider實例和consumer項目
運行兩個provider實例,發現訪問http://localhost:8081/hello/chung和http://localhost:8082/hello/chung分別能得到Hello Chung By Provider on :8081
和Hello Chung By Provider on :8082
。
運行consumer項目,訪問http://localhost:8091/hello/consumer,可以發現,我們不斷刷新頁面,結果將一直輪流爲Hello Chung By Provider on :8081
和Hello Chung By Provider on :8082
。這是由於默認Ribbon的負載均衡策略爲RoundRobinRule[輪詢]。
修改負載均衡策略
在consumer項目的配置文件添加以下代碼,重啓項目之後,負載均衡策略將變爲隨機規則,可以發現結果將不再是線性輪流變化。其他策略也可根據具體需求調整。
#負載均衡策略
provider:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule