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

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

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

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:

      Mono&lt;String&gt; bodyData = request.bodyToMono(String.class);

      System.out.println(&quot;\nsubscribing to the Mono.....&quot;);

      bodyData.subscribeOn(Schedulers.newParallel(&quot;requestBody&quot;)).subscribe(value -&gt; {
        log.debug(String.format(&quot;%n value consumed: %s&quot; ,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&lt;ServerResponse&gt; {

    private final CacheService cache;
    
    @Override
    public Mono&lt;ServerResponse&gt; handle(ServerRequest request) {
        return request.bodyToMono(String.class)
                .doOnNext(body -&gt; cache.put(body))
                .flatMap(body -&gt; ServerResponse.noContent().build());
    }
}

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:

确定