Feign默認已經整合了Hystrix,本節詳細探討Feign使用Hystrix的具體細節。git
加配置,默認Feign是不啓用Hystrix的,須要添加以下配置啓用Hystrix,這樣全部的Feign Client都會受到Hystrix保護!github
feign: hystrix: enabled: true
提供Fallback:spring
@FeignClient(name = "microservice-provider-user", fallback = UserFeignClientFallback.class) public interface UserFeignClient { @GetMapping("/users/{id}") User findById(@PathVariable("id") Long id); } @Component class UserFeignClientFallback implements UserFeignClient { @Override public User findById(Long id) { return new User(id, "默認用戶", "默認用戶", 0, new BigDecimal(1)); } }
@FeignClient(name = "microservice-provider-user", fallbackFactory = UserFeignClientFallbackFactory.class) public interface UserFeignClient { @GetMapping("/users/{id}") User findById(@PathVariable("id") Long id); } @Component @Slf4j class UserFeignClientFallbackFactory implements FallbackFactory<UserFeignClient> { @Override public UserFeignClient create(Throwable throwable) { return new UserFeignClient() { @Override public User findById(Long id) { log.error("進入回退邏輯", throwable); return new User(id, "默認用戶", "默認用戶", 0, new BigDecimal(1)); } }; } }
feign.hystrix.enabled: true
feign.hystrix.enabled: false
或直接省略不寫。app
利用Feign配置的自定義,爲指定Feign Client指定以下配置類便可,Feign配置自定義詳見:跟我學Spring Cloud(Finchley版)-10-Feign深刻ide
public class FeignDisableHystrixConfiguration { @Bean @Scope("prototype") public HystrixFeign.Builder feignBuilder() { return HystrixFeign.builder(); } }
public class FeignDisableHystrixConfiguration { @Bean @Scope("prototype") public Feign.Builder feignBuilder() { return Feign.builder(); } }
服務降級:ui
得到形成fallback的緣由:prototype
http://www.itmuch.com/spring-cloud/finchley-14/code