英文:
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<ServerResponse> handleRequest(ServerRequest serverRequest) {
return getProduct() // Service call to get the 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))
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论