在 ServerResponse 中将单声道作为 header 值传递

Pass mono as a header value in ServerResponse

我是函数式 endpoints/spring webflux 的新手,我正在尝试将 return 单声道作为 header 值,但我找不到一种方法来实现它,因为header 方法只接受字符串。

路由器功能,

@Bean
RouterFunction<ServerResponse> productRoutes() {
    return route(GET("/products").and(accept(MediaType.APPLICATION_JSON)), getAllProductsHandler());
}

处理函数,

private HandlerFunction<ServerResponse> getAllProductsHandler() {
    return req -> {

        // Here the products and the totalProducts are being returned from the service layer 

        Flux<Product> products = Flux.just(new Product("123"), new Product("234"));
        Mono<Integer> totalProducts = Mono.just(2);

        return ok()
                .header("totalCount", totalProducts)
                .body(products, Product.class);
    };
}

将 return 单声道作为 header 值的正确方法是什么?

通过链接单声道并建立您的响应。

final Mono<Integer> totalProducts = Mono.just(2);

return totalProducts.flatMap(value -> ok()
                .header("totalCount", value)
                .body(products, Product.class)
        );