Hystrix入門教程
一·什么是Hystrix毁菱?Hystrix有什么作用宪迟?使用Hystrix有哪些適用場景
Hystrix是springCloud的組件之一,Hystrix 可以讓我們在分布式系統(tǒng)中對服務間的調(diào)用進行控制
加入一些調(diào)用延遲或者依賴故障的容錯機制。Hystrix 通過將依賴服務進行資源隔離
進而阻止某個依賴服務出現(xiàn)故障時在整個系統(tǒng)所有的依賴服務調(diào)用中進行蔓延轧房;
同時Hystrix 還提供故障時的 fallback 降級機制先誉。
通過這些方法幫助我們提升分布式系統(tǒng)的可用性和穩(wěn)定性湿刽。
在高并發(fā)訪問下,這些依賴的穩(wěn)定性與否對系統(tǒng)的影響非常大,
但是依賴有很多不可控問題:如網(wǎng)絡連接緩慢,資源繁忙褐耳,暫時不可用诈闺,服務脫機等.
二·導入Hystrix相關(guān)依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
三·在啟動類上加上@EnableHystrix
@SpringBootApplication
@EnableFeignClients
@EnableApolloConfig
@ComponentScan(basePackages = "com.demo.Hystrix")
@EnableHystrix
public class ApiApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
四·在需要限流的方法中使用Hystrix
@HystrixCommand(groupKey="test-provider",
threadPoolKey="test-provider",
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "20"),//線程池大小
@HystrixProperty(name = "maximumSize", value = "30"),//最大線程池大小
@HystrixProperty(name = "maxQueueSize", value = "20"),//最大隊列長度
@HystrixProperty(name = "keepAliveTimeMinutes", value = "2")//線程存活時間
},commandProperties = {
@HystrixProperty(name = "execution.isolation.strategy",value = "THREAD"),
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "60000" ),
//此處有坑,若中斷時間不設置铃芦,上面所有參數(shù)都可能失效
@HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout",value = "300000" )
},
//fallbackMethod必須重寫雅镊,否則直接進入fallback方法中!H凶摇H逝搿!_只ⅰ卓缰!
//此處的testfallback,為第五步中重寫的方法@峡汀A欧埂!k逝椤w⑼摇!
fallbackMethod = "testfallback")
@ApiOperation(value = "Hystrix測試接口")
@PostMapping("/testHystrix")
@Log(value = "Hystrix測試接口")
public DefaultResponse<orderResponse> testHystrix(@RequestBody orderRequestVO req) {
//
......
}
五·重寫fallback方法
public DefaultResponse<Response> testfallback(HttpServletRequest request, HttpServletResponse response, @RequestBody OrderReq req) {
DefaultResponse defaultResp = new DefaultResponse();
defaultResp.setCode(Integer.parseInt(ServiceStatus.RankFAIL.getCode()));
defaultResp.setMessage("系統(tǒng)繁忙尉间,請稍后再試");
return defaultResp;
}
六· 使用總結(jié)偿乖,此處介紹三個使用過程中的三個大坑
1.必須設置中斷時間,若不設置所有參數(shù)都可能失效
2.第四步中的@HystrixCommand等注解只能在service層中使用哲嘲,在controller中使用贪薪,hystrix的限流作用會失效
3.必須重寫fallbackMethod的fallback方法,不重寫的話默認直接進入fallback方法