5

Spring Cloud之Finchley版学习(十四)-Feign使用Hystrix

 3 years ago
source link: https://www.wencst.com/archives/1395
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Spring Cloud之Finchley版学习(十四)-Feign使用Hystrix

作者: wencst 分类: JAVA,微服务,架构设计 发布时间: 2019-01-22 13:41 阅读: 1,570 次

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

  • 加配置,默认Feign是不启用Hystrix的,需要添加如下配置启用Hystrix,这样所有的Feign Client都会受到Hystrix保护!
    feign:
      hystrix:
        enabled: true
  • 提供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 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();
	}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK