英文:
How to get request body from ServerRequest object in Spring WebFlux reactive?
问题
尝试从使用Postman发送的POST请求中提取到我的Spring应用程序中的请求体。
我尝试过执行以下操作:
ServerRequest.bodyToMono(String.class).toProducer().peek()
但这返回了null。
ServerRequest.bodyToMono(String.class).block()
不再受支持。
还尝试了以下方式:
Mono<String> bodyData = request.bodyToMono(String.class);
System.out.println("\nsubscribing to the Mono.....");
bodyData.subscribeOn(Schedulers.newParallel("requestBody")).subscribe(value -> {
log.debug(String.format("\n value consumed: %s" ,value));
});
但我似乎无法在日志中看到任何内容显示出来。
英文:
Trying to extract the body of a POST request sent using Postman to my Spring application.
I've tried doing
but that returns null.
ServerRequest.bodyToMono(String.class).toProducer().peek()
ServerRequest.bodyToMono(String.class).block()
isn't supported anymore.
Also tried doing it this way:
Mono<String> bodyData = request.bodyToMono(String.class);
System.out.println("\nsubscribing to the Mono.....");
bodyData.subscribeOn(Schedulers.newParallel("requestBody")).subscribe(value -> {
log.debug(String.format("%n value consumed: %s" ,value));
});
But I can't seem to get anything to show up in the logs.
答案1
得分: 2
以下是翻译好的内容:
如果您正在寻找一个示例,展示了一个仅将请求体存储在某个缓存中的反应式 REST 端点,以下示例可以实现这一点:
public class Example implements HandlerFunction<ServerResponse> {
private final CacheService cache;
@Override
public Mono<ServerResponse> handle(ServerRequest request) {
return request.bodyToMono(String.class)
.doOnNext(body -> cache.put(body))
.flatMap(body -> ServerResponse.noContent().build());
}
}
英文:
If you are looking for an example of a reactive rest endpoint that just stores the body in some cache the following example should achieve this
public class Example implements HandlerFunction<ServerResponse> {
private final CacheService cache;
@Override
public Mono<ServerResponse> handle(ServerRequest request) {
return request.bodyToMono(String.class)
.doOnNext(body -> cache.put(body))
.flatMap(body -> ServerResponse.noContent().build());
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论