5

I am sending a POST request to my Spring application using Postman. The request has a JSON body that looks something like this:

{
        "documents": [
            {
                "id": "1",
                "text": "Piece of text 1",
                "lang": "en"
            },
            {
                "id": "2",
                "text": "Piece of text 2",
                "lang": "en"
            }
        ],
        "domain": "hr",
        "text_key": "text"
    }

I have a method set up to handle these POST requests and I need to be able to extract the above JSON data from the request body WITHOUT BLOCKING. The method I have now looks something like this:

public void requestBody(ServerRequest request) {


      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));
      });

}

However, this does nothing. I tried looking at the answers in Spring Reactive get body JSONObject using ServerRequest AND Getting String body from Spring serverrequest but to no avail. Please help out.


Update #1

thanks https://stackoverflow.com/users/1189885/chrylis-cautiouslyoptimistic

According to your answer, this is what I'm trying:

    request.bodyToMono(String.class).map(
        (String rqBody) -> {
          setRequestBody(rqBody);
          return ServerResponse.status(HttpStatus.CREATED).contentType(APPLICATION_JSON).body(rqBody, Object.class);
        }
      );


setRequestBody() is setting a global string variable to be the request body. Like this:


  public void setRequestBody (String rqBody){
    System.out.println("\nset request body called with: " + rqBody);
    request_body=rqBody;
  }

However, the global request_body variable is still null.


Update #2

This is what I'm trying to do as per your latest comment:



    RedissonClient redisson = Redisson.create();

    RBucket<Object> bucket = redisson.getBucket("requestKey");

      request.bodyToMono(String.class).doOnNext(
        (String rqBody) -> {
          bucket.set(rqBody);
        }
      );

When I go into Redis-cli and try to get requestKey, it gives me nil

dbc
  • 104,963
  • 20
  • 228
  • 340
Manav Chawla
  • 61
  • 2
  • 6

1 Answers1

3

You can't; that's the entire meaning of the reactive model. Instead, you should usually use operations like map (to modify the value by applying a function) or doOnNext (to take some action but not return a result).

If using a reactive execution model, such as Spring WebFlux, you directly return a Mono<Whatever> from your controller method, and Spring takes care of "extracting" the data for you.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152