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.
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.
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