【问题标题】:Hystrix fallback method returns nullHystrix 回退方法返回 null
【发布时间】:2020-11-22 12:10:15
【问题描述】:

我在我的 Spring Boot 微服务应用程序中实现了 feign 客户端和 hystrix。
我首先尝试测试与 feign 客户端通信 users servicealbums service, 所以我在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. Feign 错误解码器
@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

【问题讨论】:

    标签: spring microservices hystrix fallback feign


    【解决方案1】:

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

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

    后面的代码:

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

    这就是为什么您在异常中没有原因。

    【讨论】:

      猜你喜欢
      • 2017-05-03
      • 2020-01-25
      • 2017-06-18
      • 2017-10-10
      • 2018-04-05
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多