如何将 Hystrix 与 Spring WebFlux WebClient 一起使用?
How to use Hystrix with Spring WebFlux WebClients?
我正在使用 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 不兼容吗?
谢谢!
@HystrixCommand 不会真正起作用,因为 Hystrix 不会威胁 Mono/Flux 与 Java 原语有任何不同。
Hystrix 不监控 Mono 的内容,只监控调用的结果 public Mono<WeatherApiResponse> getWeatherByCityName(String cityName)
。
这个结果总是可以的,因为反应式调用链创建总是成功的。
您需要的是让 Hystrix 威胁 Mono/Flux 与众不同。
在 Spring Cloud 中,有一个 builder,用 HystrixCommand 包装 Mono/Flux。
Mono<WeatherApiResponse> call = this.getWeatherByCityName(String cityName);
Mono<WeatherApiResponse> callWrappedWithHystrix = HystrixCommands
.from(call)
.fallback(Mono.just(WeatherApiResponse.EMPTY))
.commandName("getWeatherByCityName")
.toMono();
我正在使用 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 不兼容吗?
谢谢!
@HystrixCommand 不会真正起作用,因为 Hystrix 不会威胁 Mono/Flux 与 Java 原语有任何不同。
Hystrix 不监控 Mono 的内容,只监控调用的结果 public Mono<WeatherApiResponse> getWeatherByCityName(String cityName)
。
这个结果总是可以的,因为反应式调用链创建总是成功的。
您需要的是让 Hystrix 威胁 Mono/Flux 与众不同。 在 Spring Cloud 中,有一个 builder,用 HystrixCommand 包装 Mono/Flux。
Mono<WeatherApiResponse> call = this.getWeatherByCityName(String cityName);
Mono<WeatherApiResponse> callWrappedWithHystrix = HystrixCommands
.from(call)
.fallback(Mono.just(WeatherApiResponse.EMPTY))
.commandName("getWeatherByCityName")
.toMono();