在 Spring Webflux 中压缩 2 个不同的 Mono

Zip 2 different Mono in Spring Webfux

我有以下功能

public Mono<CarAndShip> getCarAndShip(Long id) {
    Mono<Car> carMono = carService.getCar(id).subscribeOn(Schedulers.elastic());
    Mono<Ship> shipMono = shipService.getShip(id).subscribeOn(Schedulers.elastic());

    return Mono.zip(carMono, shipMono)
        .flatMap(zipMono -> {
            return new CarAndShip(zipMono.getT1(), zipMono.getT2());
        });

IntelliJ 在 return 声明中抱怨:

Required type: Mono <CarAndShip> 
Provided: Mono <Object> no
instance(s) of type variable(s) R exist so that CarAndShip conforms to Mono<? extends R>

如何将类型强制转换为所需的 CarAndShip return 类型?

Required type: Mono Provided: Mono no instance(s) of type variable(s) R exist so that CarAndShip conforms to Mono<? extends R>

如异常所述:您没有提供 Mono。

所以要么使用 map 而不是 flatMap:

return Mono.zip(carMono, shipMono)
    .map(zipMono -> new CarAndShip(zipMono.getT1(), zipMono.getT2()));

或者提供一个单声道(这里可能不是最好的方式):

return Mono.zip(carMono, shipMono)
    .flatMap(zipMono -> Mono.just(new CarAndShip(zipMono.getT1(), zipMono.getT2())));

在此示例中,您应该使用 map() 而不是 flatMap(),因为您不会返回 Mono