我有HystrixFeign客户端,我正在尝试在我的回退实现中获取原因/异常,因为我真的想知道回退的原因,所以我可以解决服务调用失败的原因。 但是下面的实现并不是我的原因。这很好用,并且后备一直在被调用。但我不知道为什么。我是Feign和Hystrix的新手。我的应用程序是用java 1。6年前编写的,这是一种增强调用。所以我不能去任何lambda表达式。
我的客户端界面定义如下
public interface MyServiceFeignClient {
@RequestLine("POST /myService/order")
@Headers("Content-Type:application/vnd.org.company.domain.order+json;version=1.0")
ServiceResponse sendOrder(String content);
}
我的FeignClientFacory如下所示
public class FeignClientFactory {
private static final Logger LOG = LoggerFactory.getLogger(FeignClientFactory.class);
private String serviceUrl;
public FeignClientFactory(final String serviceUrl) {
this.serviceUrl = serviceUrl;
}
public MyServiceFeignClient newInstance() {
return HystrixFeign.builder()
.decoder(new GsonDecoder())
.target(MyServiceFeignClient.class, serviceUrl);
}
class ClientFallbackFactory implements MyServiceFeignClient, FallbackFactory<ClientFallbackFactory> {
final Throwable cause;
public ClientFallbackFactory() {
this(null);
}
ClientFallbackFactory(Throwable cause) {
this.cause = cause;
}
// note that this method is not getting called at all
@Override
public ClientFallbackFactory create(Throwable cause) {
if (cause != null) {
String errMessage = StringUtils.isNotBlank(cause.getMessage()) ? cause.getMessage() : "unknown error occured";
LOG.debug("Client fallback called for the cause : {}", errMessage);
}
return new ClientFallbackFactory(cause);
}
// everytime this method is called as fallback and the cause is just null
@Override
public ServiceResponse sendOrder(String content) {
LOG.debug("service client api fallback called");
ServiceResponse response = new ServiceResponse();
String errMessage = (cause == null ? "service client api fallback called" : cause.getMessage());
response.setErrorMessage(errMessage);
response.setResultStatus("WARN");
return response;
}
}
}
答案 0 :(得分:0)
从open feign git hub获取retroApi示例测试用例代码并逐个开始修改帮助我解决了这个问题。以下是工作代码。
public static class ClientFallbackFactory implements MyServiceFeignClient, FallbackFactory<ClientFallbackFactory> {
@Override
public ClientFallbackFactory create(Throwable cause) {
return new PRSClientFallback(cause);
}
final Throwable cause; // nullable
public ClientFallbackFactory() {
this(null);
}
ClientFallbackFactory(Throwable cause) {
this.cause = cause;
}
@Override
public PaymentRiskServiceResponse sendOrder(String content) {
String errorMessage = (cause == null) ? "No cause returned" : cause.getMessage();
LOG.debug("Client fallback called : {} ", errorMessage);
MyServiceResponse response = new MyServiceResponse();
response.setResultStatus("WARN");
response.setErrorMessage("Client fallback called");
return response;
}
}
确保在调用HystrixFeign目标方法时键入强制转换Fallback工厂,因为Fallback类正在实现客户端接口和FallbackFactory。
return HystrixFeign.builder()
.encoder(new JacksonEncoder(mapper))
.decoder(new GsonDecoder())
.target(MyServiceFeignClient.class, prsUrl, (FallbackFactory<ClientFallbackFactory>) new ClientFallbackFactory());
您可以跟踪此问题的对话[https://github.com/OpenFeign/feign/issues/458]