Hystrix 能使你的系統在出現依賴服務失效的時候,經過隔離系統所依賴的服務,防止服務級聯失敗,同時提供失敗回退機制,更優雅地應對失效,並使你的系統能更快地從異常中恢復。java
貨船爲了進行防止漏水和火災的擴散,會將貨倉分隔爲多個,當發生災害時,將所在貨倉進行隔離就能夠下降整艘船的風險。git
熔斷器就像家裏的保險絲,當電流過載了就會跳閘,不過Hystrix的熔斷機制相對複雜一些。程序員
熔斷器開關由關閉到打開的狀態轉換是經過當前服務健康情況和設定閾值比較決定的.github
調用HystrixCommand的run方法.運行依賴邏輯web
返回執行成功結果spring
使用一個線程池來存儲當前的請求,線程池對請求做處理,設置任務返回處理超時時間,堆積的請求堆積入線程池隊列。這種方式須要爲每一個依賴的服務申請線程池,有必定的資源消耗,好處是能夠應對突發流量(流量洪峯來臨時,處理不完可將數據存儲到線程池隊裏慢慢處理)。shell
使用一個原子計數器(或信號量)來記錄當前有多少個線程在運行,請求來先判斷計數器的數值,若超過設置的最大線程個數則丟棄改類型的新請求,若不超過則執行計數操做請求來計數器+1,請求返回計數器-1。這種方式是嚴格的控制線程且當即返回模式,沒法應對突發流量(流量洪峯來臨時,處理的線程超過數量,其餘的請求會直接返回,不繼續去請求依賴的服務)。後端
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-core</artifactId> <version>1.5.12</version> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-metrics-event-stream</artifactId> <version>1.5.12</version> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-javanica</artifactId> <version>1.5.12</version> </dependency>
@Configuration public class HystrixConfig { /** * 聲明一個HystrixCommandAspect代理類,現攔截HystrixCommand的功能 */ @Bean public HystrixCommandAspect hystrixCommandAspect() { return new HystrixCommandAspect(); } }
@Service public class HelloService { @HystrixCommand(fallbackMethod = "helloError", commandProperties = { @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"), @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"), @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2")}, threadPoolProperties = { @HystrixProperty(name = "coreSize", value = "5"), @HystrixProperty(name = "maximumSize", value = "5"), @HystrixProperty(name = "maxQueueSize", value = "10") }) public String sayHello(String name) { try { Thread.sleep( 15000 ); return "Hello " + name + " !"; } catch (InterruptedException e) { e.printStackTrace(); } return null; } public String helloError(String name) { return "服務器繁忙,請稍後訪問~"; } }
@SpringBootApplication @RestController public class HystrixSimpleApplication { @Autowired private HelloService helloService; public static void main(String[] args) { SpringApplication.run( HystrixSimpleApplication.class, args ); } @GetMapping("/hi") public String hi(String name) { return helloService.sayHello( name ); } }
訪問 http://localhost:80809/hi?name=zhangsan緩存
curl -X GET -d 'name=zhangsan' http://localhost:8080/hi
返回服務器
服務器繁忙,請稍後訪問~
https://github.com/gf-huanchu...
https://github.com/Netflix/Hy...
https://blog.51cto.com/snowti...
歡迎掃碼或微信搜索公衆號《程序員果果》關注我,關注有驚喜~