一、簡單實現
-
基於上文服務消費者(
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
- 測試成功