跟我学Spring Cloud(Finchley版)-14-Feign使用Hystrix

Feign默认已经整合了Hystrix,本节详细探讨Feign使用Hystrix的具体细节。

服务降级

1 加配置,默认Feign是不启用Hystrix的,需要添加如下配置启用Hystrix,这样所有的Feign Client都会受到Hystrix保护!

feign:
  hystrix:
    enabled: true

2 提供Fallback:

@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));
  }
}

获得造成fallback的原因

@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

全局启用

feign.hystrix.enabled: true

全局禁用

feign.hystrix.enabled: false

或直接省略不写。

局部启用

利用Feign配置的自定义,为指定Feign Client指定如下配置类即可,Feign配置自定义详见:跟我学Spring&nbsp;Cloud(Finchley版)-10-Feign深入

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();
    }
}

配套代码

服务降级:

1 GitHub:https://github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-consumer-movie-feign-hystrix

2 Gitee:https://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-consumer-movie-feign-hystrix

获得造成fallback的原因:

1 GitHub:https://github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-consumer-movie-feign-hystrix-fallback-factory

2 Gitee:https://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-consumer-movie-feign-hystrix-fallback-factory

原文发布于微信公众号 - IT牧场(itmuch_com)

原文发表时间:2019-01-19

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券