1. 程式人生 > >幹貨分享微服務spring-cloud(4.負載均衡ribbon與熔斷器hystrix)

幹貨分享微服務spring-cloud(4.負載均衡ribbon與熔斷器hystrix)

技術 art client ng- mil comm fall 關閉 設置

Ribbon是一個基於httptcp的客戶端負載均衡工具

Hystrix具備服務降級、服務熔斷、線程和信號隔離、請求緩存、請求合並以及服務監控

為了方便消費者負載均衡效果,復制demo-springcloud-client1並重名為demo-springcloud-client2,修改配置文件和啟動類,服務提供者12服務名均為spring.application.name=demo-springcloud-client

技術分享圖片

技術分享圖片

修改YhqContoller實現,為了方便負載均衡觀察效果,demo-springcloud-client2項目返回字符串client2

技術分享圖片

創建消費者項目demo-springcloud-restTemplate-consumer,創建啟動類RestTemplateApplication,@EnableDiscoveryClient啟動服務發現和註冊自動配置,以便能夠發現前面註冊的服務提供者demo-springcloud-client1和demo-springcloud-client2。@EnableCircuitBreaker開啟熔斷器自動配置

技術分享圖片

創建負載平衡RestTemplate,@Bean並使用@LoadBalanced限定符。如果沒有spring-cloud-starter-ribbon依賴,@LoadBalanced的負載均衡輪詢算法將不會生效。使用spring-cloud-starter-eureka依賴,ribbon服務發現將交由Eureka提供。添加熔斷器依賴spring-cloud-starter-hystrix

技術分享圖片

創建YhqController提供rest服務restTemplateConsumer來消費之前的服務1和2,

技術分享圖片

服務通過註入的YhqService的RestTemplate對象負載均衡調用我們的服務提供者demo-springcloud-client1和demo-springcloud-client2

技術分享圖片

啟動註冊中心,啟動服務提供者1和2,啟動消費者demo-springcloud-restTemplate-consumer,瀏覽器訪問http://localhost:3331/restTemplateConsumer返回的字符串client1和client2交替出現,這是因為負載均衡輪詢的效果。

技術分享圖片

技術分享圖片技術分享圖片

熔斷器Hystrix使用fallback命令執行失敗時使用的後備方法,用來實現服務的降級處理邏輯。這時關閉服務提供者demo-springcloud-client2,瀏覽器訪問http://localhost:3331/restTemplateConsumer返回的字符串client1和我是降級邏輯交替出現

技術分享圖片

技術分享圖片

當通過註解方法實現熔斷器時,通過使用@HystrixCommand的commandProperties來設置屬性值,例如設置fallback.enabled

技術分享圖片

幹貨分享微服務spring-cloud(4.負載均衡ribbon與熔斷器hystrix)