【Spring Cloud 筆記和總結】四、熔斷器Hystrix簡單實現

一、簡單實現

  • 基於上文服務消費者(service-consumer)代碼。

  • 修改配置文件,添加:feign.hystrix.enable:true如下:

    spring:
        application:
            name: spring-cloud-consumer
    server:
        port: 9001
    eureka:
        client:
            serviceUrl:
                defaultZone: http://localhost:8000/eureka/
    feign:
      hystrix:
        enabled: true
    
  • 添加容錯回調類

    package com.lxt.serviceconsumer.hystrix;
    
    import com.lxt.serviceconsumer.dao.fegin.HelloFegin;
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.RequestParam;
    
    /**
     * @author lxt
     * @Copy Right Information: lxt
     * @Project: spring cloud
     * @CreateDate: 2018/12/16 15:58
     * @history Sr Date Modified By Why & What is modified
     * 1.2018/12/16 lxt & new
     */
    @Component
    public class HelloFeginHystrix implements HelloFegin {
        @Override
        public String hello(@RequestParam(value = "name") String name) {
            return "hello " +name+", this messge send failed ";
        }
    }
    
    
  • 修改HelloFegin添加回調fallback屬性

    @FeignClient(name= "spring-cloud-provider",fallback = HelloFeginHystrix.class)
    
  • 測試

    • 分別啓動註冊中心、服務提供者和服務消費者
    • 瀏覽器訪問localhost:9001/hello/lxt,返回hello lxt,this is first messge
    • 停止服務提供者,再次訪問
    • 返回hello lxt,this messge send failed
    • 測試成功

二、相關

  • 父模塊介紹傳送門
  • 源碼地址傳送門
  • 參考
    • https://www.cnblogs.com/carrychan/p/9529418.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章