一、fallback
-
yml
server: port: 80 spring: application: name: cloud-provider-hystrix-order eureka: client: register-with-eureka: true #示表不向注册中心注册自己 fetch-registry: true #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务 service-url: defaultZone: http://eureka7001.com:7001/eureka/ ####################以下配置需要新增(ribbon相关配置和Feign超时相关)################## #全局配置 # 请求连接的超时时间 默认的时间为 1 秒 ribbon: ConnectTimeout: 5000 # 请求处理的超时时间 ReadTimeout: 5000 # feign 配置 feign: hystrix: enabled: true # hystrix 配置 hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 3000
-
service
@Component @FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentHystixServiceFallBackImpl.class) public interface PaymentHystrixService { @GetMapping("/payment/hystrix/ok/{id}") String paymentInfo_OK(@PathVariable("id") Integer id); @GetMapping("/payment/hystrix/timeout/{id}") String paymentInfo_TimeOut(@PathVariable("id") Integer id); }
-
fallbackImpl
@Component public class PaymentHystixServiceFallBackImpl implements PaymentHystrixService { @Override public String paymentInfo_OK(Integer id) { return "服务降级"; } @Override public String paymentInfo_TimeOut(Integer id) { return "服务降级"; } }
二、fallbackFactory
-
yml同上
-
service
@Component @FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallbackFactory = PaymentHytrixServiceFallBackFactory.class) public interface PaymentHystrixService { @GetMapping("/payment/hystrix/ok/{id}") String paymentInfo_OK(@PathVariable("id") Integer id); @GetMapping("/payment/hystrix/timeout/{id}") String paymentInfo_TimeOut(@PathVariable("id") Integer id); }
-
fallbackFactory
@Component public class PaymentHytrixServiceFallBackFactory implements FallbackFactory<PaymentHystrixService> { @Override public PaymentHystrixService create(Throwable throwable) { return new PaymentHystrixService() { @Override public String paymentInfo_OK(Integer id) { return "服务降级"; } @Override public String paymentInfo_TimeOut(Integer id) { return "服务降级"; } }; } }
三、两者结合
-
fallbackImpl同一
-
修改fallbackFactory
@Component public class PaymentHytrixServiceFallBackFactory implements FallbackFactory<PaymentHystrixService> { @Override public PaymentHystrixService create(Throwable throwable) { PaymentHystixServiceFallBackImpl paymentHystixServiceFallBack = new PaymentHystixServiceFallBackImpl(); return paymentHystixServiceFallBack; } }