Hystrix入門教程


Hystrix入門教程

一·什么是Hystrix?Hystrix有什么作用?使用Hystrix有哪些適用場景

Hystrix是springCloud的組件之一,Hystrix 可以讓我們在分布式系統中對服務間的調用進行控制
加入一些調用延遲或者依賴故障的容錯機制。Hystrix 通過將依賴服務進行資源隔離
進而阻止某個依賴服務出現故障時在整個系統所有的依賴服務調用中進行蔓延;
同時Hystrix 還提供故障時的 fallback 降級機制。
通過這些方法幫助我們提升分布式系統的可用性和穩定性。
在高並發訪問下,這些依賴的穩定性與否對系統的影響非常大,
但是依賴有很多不可控問題:如網絡連接緩慢,資源繁忙,暫時不可用,服務脫機等.

二·導入Hystrix相關依賴

        <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" ),
            //此處有坑,若中斷時間不設置,上面所有參數都可能失效
            @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout",value = "300000" )
             },
             //fallbackMethod必須重寫,否則直接進入fallback方法中!!!!!!
             //此處的testfallback,為第五步中重寫的方法!!!!!!
            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("系統繁忙,請稍后再試");
        return defaultResp;
    }

六· 使用總結,此處介紹三個使用過程中的三個大坑

1.必須設置中斷時間,若不設置所有參數都可能失效

2.第四步中的@HystrixCommand等注解只能在service層中使用,在controller中使用,hystrix的限流作用會失效

3.必須重寫fallbackMethod的fallback方法,不重寫的話默認直接進入fallback方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM