如何在包装器类中合并两个Spring Boot微服务响应

时间:2018-06-24 18:18:22

标签: java spring spring-boot microservices spring-webflux

我是Spring引导微服务和探索webflux框架的新手。我正在尝试将两个微服务的响应合并到一个包装器类中,以将响应包含在正确的JSON中。下面是该方案的详细信息。

微服务1:http://localhost:8080/products 在这个微服务的控制器中,它返回Flux,我得到了

[
    {
        "id": "5b2fd1e5f57d731904c54ad7",
        "name": "Product3",
        "price": "30"
    },
    {
        "id": "5b2fd1e4j9fdj3kds9djkj43",
        "name": "Product2",
        "price": "20"
    }
]

微服务2:http://localhost:8181/person 在第二个服务的控制器中,它返回的是Mono,为此,我也得到如下正确的响应,

{
    "id": ehj8u3jmodmdj,
    "name": "PersonXXX",
    "email": "PersonXXX@somecorp.com"
}

现在,我想创建另一个微服务http://localhost:8282/personproduct,该微服务应将上述两个微服务的结果合并到如下的包装器类中,

{
    {
        "id": ehj8u3jmodmdj,
        "name": "PersonXXX",
        "email": "PersonXXX@somecorp.com"
    },

    [
        {
            "id": "5b2fd1e5f57d731904c54ad7",
            "name": "Product3",
            "price": "30"
        },
        {
            "id": "5b2fd1e4j9fdj3kds9djkj43",
            "name": "Product2",
            "price": "20"
        }
    ]

}

现在,我对Product和Person类都有一个Parent类Entity,并且正在通过WebClient调用上述微服务,并使用Flux.concat(personResp,productResp)来简化响应。其中personResp的类型为Mono,而productResp的类型为Flux,但我仅在文本而不是JSON中获得此(第三)微服务的响应,如下所示,

data:{"id":ehj8u3jmodmdj,"name":"PersonXXX","email":"PersonXXX@somecorp.com"}
data:{"id":"5b2fd1e5f57d731904c54ad7","name":"Product3","price":"30"}
data:{"id":"5b2fd1e4j9fdj3kds9djkj43","name":"Product2","price":"20"}

这可能是由于每个元素都作为不同的流发送的。

所以只想知道是否有任何方法可以在一个包装类中组合两个响应,而无需在对这两个服务进行的任何调用上使用block()方法。

更新

目前,我称产品微服务为

clientProd.get().uri(productUrl)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .retrieve().bodyToFlux(Product.class).onErrorReturn(new Product());

类似的人服务

clientPerson.get().uri(personUri)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .retrieve().bodyToMono(Person.class).onErrorReturn(new Person());

并使用Flux.concat()进行连接,

谢谢。

1 个答案:

答案 0 :(得分:1)

正确的方法是将这些响应映射到类:

public class Product{
    private Long id;
    private String name;
    private Double price;

    //constructors, getters, setters
}

public class Person{
    private Long id;
    private String name;
    private String mail;

    //constructors, getters, setters
}

public class Entity{
    private Person person;
    private List <Product> products;

    //constructors, getters, setters
}

通过这种方式,您可以根据需要(正在调用的API类型)使用三个不同的POJO