1. 程式人生 > 其它 >SpringCloud微服務之Hystrix熔斷

SpringCloud微服務之Hystrix熔斷

熔斷和降級的配置基本差不多,不同之處就在於使用HystrixCommand註解
熔斷就是在此註解中通過配置commandProperties完成。

在服務端配置熔斷

在Service層,當然也可以在controller層配置

service層

@HystrixCommand(fallbackMethod = "breakerFallback", commandProperties = {
            //開啟熔斷
            @HystrixProperty(name = "circuitBreaker.enabled", value =
"true"), //熔斷觸發的最小個數/10s,預設值20 @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), //熔斷多少秒後去嘗試請求,預設值5000 @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"
), //失敗率達到多少百分比後熔斷,預設值50 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000") }) public String breaker
(int id){ log.info("providerService--->{}",id); if(id==404){ throw new RuntimeException("模擬熔斷錯誤"); } return "id:"+id+"--->正常業務"; } public String breakerFallback(int id){ return "id:"+id+"--->熔斷處理"; }

controller層

@RestController
@RequestMapping("user")
@Slf4j
@DefaultProperties(defaultFallback = "timeOutMethod")
public class UserControllerProvider {
    @Autowired
    UserService userService;

    @RequestMapping("Breaker/{id}")
    public String CircuitBreaker(@PathVariable("id") Integer id) {
        log.info("CircuitBreaker()--->  執行");
        return userService.breaker(id);
    }
}

在客戶端呼叫服務端暴露的介面

@RestController
@RequestMapping("user")
@Slf4j
public class UserControllerComsumer {
    @Autowired
    UserService userService;

    @RequestMapping("Breaker/{id}")
    public String circuitBreaker(@PathVariable("id") int id){
        log.info("UserControllerComsumer-circuitBreaker->{}",id);
        /*if(id==404)
            throw new RuntimeException("消費者端降級");*/
        return userService.CircuitBreaker(id);
    }
}

瀏覽器中測試:在10秒內請求10次如果有百分之六十服務端都是返回的降級方法資訊,那麼就會開啟斷路器,不管是正確還是錯誤請求都會出發降級。

訪問時路徑攜帶404服務端就會丟擲錯誤

public String breaker(int id){
        log.info("providerService--->{}",id);
        if(id==404){
            throw new RuntimeException("模擬熔斷錯誤");
        }
        return "id:"+id+"--->正常業務";
    }

正常情況:
在這裡插入圖片描述
攜帶引數404,短時間內快速請求多次觸發配置的斷路。即使攜帶引數為1服務端也會觸發降級
在這裡插入圖片描述