如何从Spring WebFlux响应式中的ServerRequest对象获取请求主体?

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

How to get request body from ServerRequest object in Spring WebFlux reactive?

问题

尝试从使用Postman发送的POST请求中提取到我的Spring应用程序中的请求体。

我尝试过执行以下操作:

  1. ServerRequest.bodyToMono(String.class).toProducer().peek()

但这返回了null。

ServerRequest.bodyToMono(String.class).block() 不再受支持。

还尝试了以下方式:

  1. Mono<String> bodyData = request.bodyToMono(String.class);
  2. System.out.println("\nsubscribing to the Mono.....");
  3. bodyData.subscribeOn(Schedulers.newParallel("requestBody")).subscribe(value -> {
  4. log.debug(String.format("\n value consumed: %s" ,value));
  5. });

但我似乎无法在日志中看到任何内容显示出来。

英文:

Trying to extract the body of a POST request sent using Postman to my Spring application.
I've tried doing

ServerRequest.bodyToMono(String.class).toProducer().peek()
but that returns null.

ServerRequest.bodyToMono(String.class).block() isn't supported anymore.

Also tried doing it this way:

  1. Mono&lt;String&gt; bodyData = request.bodyToMono(String.class);
  2. System.out.println(&quot;\nsubscribing to the Mono.....&quot;);
  3. bodyData.subscribeOn(Schedulers.newParallel(&quot;requestBody&quot;)).subscribe(value -&gt; {
  4. log.debug(String.format(&quot;%n value consumed: %s&quot; ,value));
  5. });

But I can't seem to get anything to show up in the logs.

答案1

得分: 2

以下是翻译好的内容:

如果您正在寻找一个示例,展示了一个仅将请求体存储在某个缓存中的反应式 REST 端点,以下示例可以实现这一点:

  1. public class Example implements HandlerFunction<ServerResponse> {
  2. private final CacheService cache;
  3. @Override
  4. public Mono<ServerResponse> handle(ServerRequest request) {
  5. return request.bodyToMono(String.class)
  6. .doOnNext(body -> cache.put(body))
  7. .flatMap(body -> ServerResponse.noContent().build());
  8. }
  9. }
英文:

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

  1. public class Example implements HandlerFunction&lt;ServerResponse&gt; {
  2. private final CacheService cache;
  3. @Override
  4. public Mono&lt;ServerResponse&gt; handle(ServerRequest request) {
  5. return request.bodyToMono(String.class)
  6. .doOnNext(body -&gt; cache.put(body))
  7. .flatMap(body -&gt; ServerResponse.noContent().build());
  8. }
  9. }

huangapple
  • 本文由 发表于 2020年10月14日 05:07:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64343174.html
匿名

发表评论

匿名网友

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

确定