Webflux 返回 Mono 并使用 Mono 中的信息设置标头

huangapple go评论67阅读模式
英文:

Webflux returning Mono and using info in Object in Mono to set header

问题

现在,我想要在响应头部完成响应,并且需要获取创建的产品ID。

在我的示例中,我使用了block(),这违反了处理程序的响应性原则。

如何在不违反响应性原则的情况下执行此任务?

英文:

Let's say my Webflux handler returns a Mono on a product creation
That's easy to do.

But now, I want to complete the response with a location in the header.
To do so, I need to get the created product ID.

In my example, I used a block() which fails the reactive idea of the handler.

public Mono<ServerResponse> handleRequest(ServerRequest serverRequest) {
        ...
        Mono<Product> monoProduct = // Service call to get the Mono<Product>
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                             .location(URI.create(String.format("/api/products/%s",
                                                                monoProduct.block().getId()))))
                             .body(monoProduct), ProductResponse.class);
    }

How can I perform such a task without breaking the reactive principles?

答案1

得分: 1

你不需要真的阻塞。你需要构建一个将不同操作符组合起来的响应式流。

在你的情况下,它可能看起来像这样:

public Mono<ServerResponse> handleRequest(ServerRequest serverRequest) {
    return getProduct() // 调用服务以获取 Mono<Product>
            .map(product -> mapToResponse(product)) // Product -> ProductResponse
            .flatMap(response ->
                    ServerResponse.ok()
                            .contentType(MediaType.APPLICATION_JSON)
                            .location(URI.create(String.format("/api/products/%s", response.getId())))
                            .body(BodyInserters.fromValue(response))
            );
}
英文:

You don't really need to block. You need to build reactive flow combining different operators.

In your case it could look like

public Mono&lt;ServerResponse&gt; handleRequest(ServerRequest serverRequest) {
    return getProduct() // Service call to get the Mono&lt;Product&gt;
            .map(product -&gt; mapToResponse(product)) // Product -&gt; ProductResponse
            .flatMap(response -&gt;
                    ServerResponse.ok()
                            .contentType(MediaType.APPLICATION_JSON)
                            .location(URI.create(String.format(&quot;/api/products/%s&quot;, response.getId())))
                            .body(BodyInserters.fromValue(response))
            );
}

huangapple
  • 本文由 发表于 2023年2月16日 03:02:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定