在一個項目中,系統可能被拆分紅多個服務,例如用戶、訂單和庫存等。java
這裏存在這服務調用服務的狀況,例如,客戶端調用訂單服務,訂單服務又調用庫存服務。git
此時若庫存服務響應緩慢,會直接致使訂單服務的線程被掛起,以等待庫存申請服務的響應,在漫長的等待以後用戶會由於請求庫存失敗而獲得建立訂單失敗的結果。github
若是在高併發下,因這些掛起的線程在等待庫存服務的響應而未能得到釋放,會似的後續到來的請求被阻塞,最終致使訂單服務也不可用。web
在分佈式架構中,斷路器模式的做用也是相似的,當某個服務單元發生故障以後,經過斷路器的故障監控,向調用方返回一個錯誤響應,而不是漫長的等待。spring
首先,添加斷路器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 @LoadBalanced RestTemplate 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].