【问题标题】:How to use Hystrix with Spring WebFlux WebClients?如何将 Hystrix 与 Spring WebFlux WebClients 一起使用?
【发布时间】:2018-11-14 05:41:51
【问题描述】:

我正在使用带有功能端点的 Spring WebFlux 来创建 API。为了提供我想要的结果,我需要使用外部 RESTful API,并以异步方式执行此操作,我正在使用 WebClient 实现。它运行良好,如下所示:

public WeatherWebClient() {
    this.weatherWebClient = WebClient.create("http://api.openweathermap.org/data/2.5/weather");
}

public Mono<WeatherApiResponse> getWeatherByCityName(String cityName) {
    return weatherWebClient
            .get()
            .uri(uriBuilder -> uriBuilder
                                .queryParam("q", cityName)
                                .queryParam("units", "metric")
                                .queryParam("appid", API_KEY)
                                .build())
            .accept(APPLICATION_JSON)
            .retrieve()
            .bodyToMono(WeatherApiResponse.class);
}

因为它执行网络访问,所以它是 NetFlix OSS Hystrix 的一个很好的用例。我试过使用 spring-cloud-starter-netflix-hystrix,将@HystrixCommand 添加到上面的方法中,但没有办法让它跳闸,即使我设置了错误的 URL(404)或错误的 API_KEY(401) .

我认为这可能是与 WebFlux 本身的兼容性问题,但设置属性 @HystrixProperty(name="circuitBreaker.forceOpen", value="true") 确实会强制回退方法运行。

我错过了什么吗?这种方法是否与 Spring WebClients 不兼容?

谢谢!

【问题讨论】:

    标签: spring-cloud-netflix spring-webflux hystrix project-reactor


    【解决方案1】:

    @HystrixCommand 不会真正起作用,因为 Hystrix 不会威胁 Mono/Flux 与 Java 原语有任何不同。

    Hystrix 不监控 Mono 的内容,只监控调用 public Mono&lt;WeatherApiResponse&gt; getWeatherByCityName(String cityName) 的结果。

    这个结果总是可以的,因为反应式调用链的创建总是会成功的。

    您需要的是让 Hystrix 以不同的方式威胁 Mono/Flux。 在 Spring Cloud 中,有一个builder,用来封装 Mono/Flux 和 HystrixCommand。

    Mono<WeatherApiResponse> call = this.getWeatherByCityName(String cityName);
    
    Mono<WeatherApiResponse> callWrappedWithHystrix = HystrixCommands
                                    .from(call)
                                    .fallback(Mono.just(WeatherApiResponse.EMPTY))
                                    .commandName("getWeatherByCityName")
                                    .toMono();
    

    【讨论】:

    • 嘿...在我的映射器行为中调用哪一个?调用还是调用WrappedWithHystrix?
    • 你需要使用callWrappedWithHystrix一个
    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 2015-03-24
    • 2020-04-10
    • 1970-01-01
    • 2019-09-27
    • 2021-09-11
    • 2015-06-19
    • 1970-01-01
    相关资源
    最近更新 更多