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

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

我正在使用 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);
}

这工作正常并产生如下响应:
{
    "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
}

但我只对 感兴趣“温度”属性(主要 -> 温度)。我如何转换响应(例如,使用 Jackson 的 ObjectMapper)以仅返回 “温度”以 react /非阻塞方式值(value)?

我知道第一件事是用“.exchange()”替换“.retrieve()”,但我不知道如何让它工作。

PS:这是我在这里的第一个问题。如果我做错了什么或者您需要更多详细信息,请告诉我。

谢谢!

最佳答案

您需要创建与服务器发送的响应相对应的类型。一个非常小的例子可能是这样的:

@JsonIgnoreProperties(ignoreUnknown = true)
public class WeatherResponse {
    public MainWeatherData main;
}

MainWeatherData类可以是:
@JsonIgnoreProperties(ignoreUnknown = true)
public class MainWeatherData {
    public String temp;
}

最后,您可以使用 WeatherResponsebodyToMono :
...
   .retrieve()
   .bodyToMono(WeatherResponse.class);
@JsonIgnoreProperties(ignoreUnknown = true)注释指示 Jackson 在遇到 JSON 字符串中不存在于您的 POJO 中的任何值时不要给出任何错误。

您可以访问 WeatherResponse带有链接的对象 map运算符(operator):
getWeatherByCityName(cityName)
     .map(weatherResponse -> weatherResponse.main.temp)  

关于functional-programming - 如何以非阻塞方式解析 Spring 5 WebClient 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50659316/

相关文章:

java - 在 RxJava 中使用 onErrorReturn 和 retryWhen

c++ - 为什么用 std::function 重载函数需要中间变量

ios - Swift 编译器错误 : "Expression too complex" on a string concatenation

java - Spring Webflux 如何将 WebClient Junit 的响应模拟为 Mono.error

java - 自动将 JSON 字节从 RabbitMQ 队列转换为对象

java - Dropwizard @QueryParam 返回 null 而不是读取参数

Spring webflux和从数据库读取

data-structures - 缺点有什么优点?

scala - 列表模式匹配添加基于案例对象的过滤

java - FasterXML Jackson 2 中 SerializerBase 的替代类是什么?