我使用带有函数端点的Spring来创建WebFlux。为了提供我想要的结果,我需要使用一个外部的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操作系统Hystrix的一个很好的用例。我尝试过使用spring netflix-hystrix,在上面的方法中添加了@HystrixCommand,但是没有办法让它跳过电路,即使我设置了一个错误的URL (404)或错误的API_KEY (401)。
我认为这可能是一个与WebFlux本身兼容的问题,但设置属性WebFlux value="true")确实会迫使回退方法运行。
我是不是遗漏了什么?这种方法与Spring不兼容吗?
谢谢!
发布于 2018-07-15 07:48:22
@HystrixCommand无法真正工作,因为Hystrix对Mono/Flux的威胁与Java原语没有任何不同。
Hystrix不监视Mono的内容,而只监视调用public Mono<WeatherApiResponse> getWeatherByCityName(String cityName)
的结果。
这个结果总是可以的,因为反应式调用链的创建总是成功的.
你需要做的是,使黑线威胁Mono/Flux不同。在Spring中,有一个构建器,可以用HystrixCommand包装Mono/Flux。
Mono<WeatherApiResponse> call = this.getWeatherByCityName(String cityName);
Mono<WeatherApiResponse> callWrappedWithHystrix = HystrixCommands
.from(call)
.fallback(Mono.just(WeatherApiResponse.EMPTY))
.commandName("getWeatherByCityName")
.toMono();
https://stackoverflow.com/questions/50688177
复制