小编Mic*_*gme的帖子

如何以非阻塞方式解析 Spring 5 WebClient 响应?

我正在使用 Spring WebFlux WebClient 从外部 API 检索数据,如下所示:

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

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

这工作正常并产生如下响应:

{
    "coord":{
        "lon":-47.06,
        "lat":-22.91
    },
    "weather":[
    {
        "id":800,
        "main":"Clear",
        "description":"clear sky",
        "icon":"01d"
    }
    ],
    "base":"stations",
    "main":{
        "temp":16,
        "pressure":1020,
        "humidity":67,
        "temp_min":16,
        "temp_max":16
    },
    "visibility":10000,
    "wind":{
        "speed":1,
        "deg":90
    },
    "clouds":{
        "all":0
    },
    "dt":1527937200,
    "sys":{
        "type":1,
        "id":4521,
        "message":0.0038,
        "country":"BR",
        "sunrise":1527932532,
        "sunset":1527971422
    },
    "id":3467865,
    "name":"Campinas",
    "cod":200
} …
Run Code Online (Sandbox Code Playgroud)

functional-programming reactive-programming jackson project-reactor spring-webflux

7
推荐指数
1
解决办法
1万
查看次数

如何在Spring WebFlux WebClients中使用Hystrix?

我正在使用具有功能端点的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);
}
Run Code Online (Sandbox Code Playgroud)

由于这会执行网络访问,因此它是NetFlix OSS Hystrix的一个很好的用例.我已经尝试过使用spring-cloud-starter-netflix-hystrix,将@HystrixCommand添加到上面的方法中,但即使我设置了错误的URL(404)或错误的API_KEY(401),也无法使其跳闸. .

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

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

谢谢!

project-reactor hystrix spring-cloud-netflix spring-webflux

7
推荐指数
1
解决办法
3348
查看次数