springcloud之Hystrix初識篇—結合ResTeamplate小述

PS:觀看該篇文章前請先參考上一篇文章

捕獲熔斷異常:降級方法中可以添加一個異常參數,用於抓取正式調用請求異常的信息。

/**
 * fallbackMethod:降級方法【PS:該方法最多隻能添加下面這2個參數,或只接收請求方法的參數】
 * @param body 請求方法的參數
 * @param throwable 異常信息
 * @return
 */
public String sendFail(String body,Throwable throwable){
        logger.info("異常信息:"+throwable);
        //備用邏輯
        return "restTemplate熔斷:"+body;
    }

再次請求:

ResTeamplate請求的熔斷節點:

根據之前的描述可以分析到消費者調用提供者,提供者服務異常消費者執行熔斷操作,所以是提供者異常執行的熔斷?

示例1:

提供者:

@RequestMapping("/hystrixRestTemplate/Code")
    public String hystrixRestTemplateSend(@RequestBody String body){
        System.out.println(body);
        String[] str = new String[3];
        //數組越界
        System.out.println(str[3]);
        return port+":"+body;
    }

消費者調用:
控制檯打印異常:請求返回:

總結:提供者服務異常,消費者執行熔斷操作

示例2:
前提:提供者正常。
消費者:

    @HystrixCommand(fallbackMethod="sendFail")
    public String hystrixRestTemplateSend(String body) {
        String url = "http://test1/eureka-clinet1/hystrixRestTemplate/Code";
        ResponseEntity<String> result = restTemplate.postForEntity(url,body,String.class);
        System.out.println("提供者返回結果:"+result);
        try {
            //線程睡眠時間過長,即使服務提供者返回正常方法也會熔斷
            Thread.sleep(10000);
        }catch (Exception e){

        }
        return result.getBody();
        //return "test";
    }

調用請求:
控制檯信息:
請求返回信息:

原因:控制檯打印出一個異常HystrixTimeoutException,因爲在提供者返回結果後我們讓線程sleep10秒,導致熔斷器認爲方法超時自動執行了熔斷操作,走了降級方法。

總結:RestTemplate調用模式中熔斷節點在被@HystrixCommand所修飾的方法,而不是被調用的提供者方法。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章