OpenFeign 集成Hystrix 开启后备模式
步骤: 1.在配置文件中开启Hystrix 熔断功能:feign.hystrix.eabled:true 2.FeignClient 注解的fallback 和fallbackFactory属性 两种属性都是用于配置响应回退,但是不可以同时使用 fallbackFactory 能够获取OpenFeign 调用抛出的异常
/**
* <h1>AuthorityFeignClient 后备 fallback</h1>
* */
@Slf4j
@Component
public class AuthorityFeignClientFallback implements AuthorityFeignClient {
@Override
public JwtToken getTokenByFeign(UsernameAndPassword usernameAndPassword) {
log.info("authority feign client get token by feign request error " +
"(Hystrix Fallback): [{}]", JSON.toJSONString(usernameAndPassword));
return new JwtToken("qinyi");
}
}
/**
* <h1>与 Authority 服务通信的 Feign Client 接口定义</h1>
* */
@FeignClient(
contextId = "AuthorityFeignClient", value = "e-commerce-authority-center",
// fallback = AuthorityFeignClientFallback.class
fallbackFactory = AuthorityFeignClientFallbackFactory.class
)
public interface AuthorityFeignClient {
/**
* <h2>通过 OpenFeign 访问 Authority 获取 Token</h2>
* */
@RequestMapping(value = "/ecommerce-authority-center/authority/token",
method = RequestMethod.POST,
consumes = "application/json", produces = "application/json")
JwtToken getTokenByFeign(@RequestBody UsernameAndPassword usernameAndPassword);
}
/**
* <h1>OpenFeign 集成 Hystrix 的另一种模式</h1>
* */
@Slf4j
@Component
public class AuthorityFeignClientFallbackFactory
implements FallbackFactory<AuthorityFeignClient> {
@Override
public AuthorityFeignClient create(Throwable throwable) {
log.warn("authority feign client get token by feign request error " +
"(Hystrix FallbackFactory): [{}]", throwable.getMessage(), throwable);
return new AuthorityFeignClient() {
@Override
public JwtToken getTokenByFeign(UsernameAndPassword usernameAndPassword) {
return new JwtToken("qinyi-factory");
}
};
}
}