javascript
(七)SpringBoot+SpringCloud —— 集成断路器
2019獨角獸企業重金招聘Python工程師標準>>>
斷路器簡介
在一個項目中,系統可能被拆分成多個服務,例如用戶、訂單和庫存等。
這里存在這服務調用服務的情況,例如,客戶端調用訂單服務,訂單服務又調用庫存服務。
此時若庫存服務響應緩慢,會直接導致訂單服務的線程被掛起,以等待庫存申請服務的響應,在漫長的等待之后用戶會因為請求庫存失敗而得到創建訂單失敗的結果。
如果在高并發下,因這些掛起的線程在等待庫存服務的響應而未能獲得釋放,會似的后續到來的請求被阻塞,最終導致訂單服務也不可用。
在分布式架構中,斷路器模式的作用也是類似的,當某個服務單元發生故障之后,通過斷路器的故障監控,向調用方返回一個錯誤響應,而不是漫長的等待。
快速入門
首先,添加斷路器hystrix的依賴。
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-hystrix</artifactId></dependency>接著在工程的主類,添加注解@EnableCircuitBreaker:
package cn.net.bysoft.owl.bookstore.web.console;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate;@SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker public class OwlBookstoreWebConsoleApplication {@Bean@LoadBalancedRestTemplate restTemplate() {return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(OwlBookstoreWebConsoleApplication.class, args);} }接著,就可以使用斷路器了,可以添加@HystrixCommand注解,對調用服務的方法進行修飾:
@HystrixCommand(fallbackMethod = "findByIdFallback")public User findById(Long id) {UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://SERVICE-USER/users/{id}").build().expand(id).encode();URI uri = uriComponents.toUri();return restTemplate.getForObject(uri, User.class);}public User findByIdFallback(Long id) {return null;}fallbackMethod是服務發生異常時,回調的降級處理函數,該函數的參數和返回值要與調用函數一致。
斷路器的默認超時時間為2000毫秒。當被斷路器修飾的函數執行超過這個值,將觸發斷路器的服務降級,該參數是可以設置的。
斷路器配置
全局配置屬性:hystrix.[attr].default.
實例配置屬性:hystrix.[attr].[key].
execution配置
Github
https://github.com/XuePeng87/owl-bookstore
轉載于:https://my.oschina.net/u/2450666/blog/1499040
總結
以上是生活随笔為你收集整理的(七)SpringBoot+SpringCloud —— 集成断路器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python-数据结构-大学生-航空订票
- 下一篇: Spring MVC面试题