Hystrix回退方法返回null



我在spring-boot微服务应用程序中实现了foreign客户端和hystrix
我首先尝试测试与外部客户端进行CCD_ 1到CCD_,所以我在albums service抛出了一个异常,以检查users service错误解码器是否能够捕捉到该异常,然后触发回退方法。

它起作用了,但cause总是在第一次为空,之后我可以看到我想要看到的错误消息。

有人能告诉我是不是出了什么问题吗
这是我的代码。

  1. 用户服务Feign客户端
@FeignClient(name = "albums-ws", fallbackFactory = AlbumsFallbackFactory.class)
public interface AlbumServiceClient {
@GetMapping(path = "users/{userId}/albums")
List<AlbumDetailResponse> getAlbums(@PathVariable("userId") String userId);
}
  1. 后备工厂
@Component
public class AlbumsFallbackFactory implements FallbackFactory<AlbumServiceClient> {
@Override
public AlbumServiceClient create(Throwable cause) {
return new AlbumServiceClientFallback(cause);
}
}
public class AlbumServiceClientFallback implements AlbumServiceClient {
private final Throwable cause;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public AlbumServiceClientFallback(Throwable cause) {
this.cause = cause;
}
@Override
public List<AlbumDetailResponse> getAlbums(String userId) {
logger.error("An exception took place: " + cause.getMessage());
return new ArrayList<>();
}
}
  1. 伪错误解码器
@Component
public class FeignErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
switch(response.status()) {
case 400:
break;
case 404:
if(methodKey.contains("getAlbums")) {
return new ResponseStatusException(HttpStatus.valueOf(response.status()), response.reason());
}
break;
default:
return new Exception(response.reason());
}
return null;
}
}
  1. 触发第一个回退
2020-08-02 12:42:27.836 ERROR 24772 --- [ HystrixTimer-1] c.a.p.a.u.P.f.AlbumServiceClientFallback : An exception took place: null
  1. 之后
2020-08-02 12:43:07.672 DEBUG 24772 --- [rix-albums-ws-2] c.a.p.a.u.P.feign.AlbumServiceClient     : [AlbumServiceClient#getAlbums] User not found with id: f5b313e2-411f-4fc3-95e7-9aa5c43c286c

Hystrix具有org.springframework.cloud.netflix.feign.HystrixTargeter类。targetWithFallbackFactory方法中有一条注释:

我们从后备工厂中抽取一个后备样本来检查返回与带注释的外键兼容的回退界面

和之后的代码:

Object exampleFallback = fallbackFactory.create(new RuntimeException());

这就是为什么你没有例外的理由。

最新更新