springcloud搭建(九)hystrix服務熔斷

1.創建hystrix項目microservice-student-provider-hystrix-1004

2.額外添加hystrix依賴

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

3.修改application.yml文件

server:
  port: 1004
  context-path: /

eureka:
  instance:
    hostname: localhost  #eureka客戶端主機實例名稱
    appname: microservice-student  #客戶端服務名
    instance-id: microservice-student-hystrix:1004 #客戶端實例名稱
    prefer-ip-address: true #顯示IP

4.啓動類上增加@EnableCircuitBreaker

5.controller中增加@HystrixCommand方法及fallbackMethod方法

    /**
     * 獲取信息
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping(value="/getInfo")
    @HystrixCommand(fallbackMethod="getInfoFallback")
    public Map<String,Object> getInfo() throws InterruptedException{
        // 默認超時1秒
        Thread.sleep(4000);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code", 200);
        map.put("info", "業務數據xxxxx");
        return map;
    }
    
    public Map<String,Object> getInfoFallback() throws InterruptedException{
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code", 500);
        map.put("info", "系統出錯,稍後重試");
        return map;
    }

6.consumer中增加測試方法

    @SuppressWarnings("unchecked")
    @GetMapping(value="/getInfo")
    @ResponseBody
    public Map<String,Object> getInfo(){
        return restTemplate.getForObject(PRE_HOST+"/student/getInfo/", Map.class);
    }

不超時走getInfo方法,否則走getInfoFallback方法

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