简体   繁体   中英

How to send Mono of ResponseEntity of a class which has Flux/Mono attribute

I am creating API with Spring webflux to measure the response time as compare to Spring MVC which has same code.

In Spring MVC , I send response with ResponseEntity<HttpResponse> .

public class HttpResponse {
    private Date timestamp = new Date();
    private int status;
    private boolean error;
    private String message;
    private Object data;

    public Date getTimestamp() {
        return timestamp;
    }
    public int getStatus() {
        return status;
    }

    public boolean isError() {
        return error;
    }

    public String getMessage() {
        return message;
    }

    public Object getData() {
        return data;
    }
    public HttpResponse() {
        super();
    }
    public HttpResponse(int status, boolean error, String message, Object data) {
        super();
        this.status = status;
        this.error = error;
        this.message = message;
        this.data = data;
    }
}

And this is my return statement in requestMapping method:

return new ResponseEntity<HttpResponse>(new HttpResponse(httpStatus.value(), error, message, responseObject), httpStatus);

httpStatus is instance of HttpStatus

error is a boolean

message is a String

responseObject is a Object

This works fine, I get proper response.

In Spring webflux , I have used Mono<ResponseEntity<HttpResponse>> instead of ResponseEntity<HttpResponse> and this is the return statement in requestMapping method.

return Mono.just(new ResponseEntity<HttpResponse>(new HttpResponse(httpStatus.value(), error, message, responseObj), httpStatus));

this gives this response

{
    "timestamp": "2018-06-25T16:18:09.949+0000",
    "status": 200,
    "error": false,
    "message": "23",
    "data": {
        "scanAvailable": true
    }
}

I have passed a Mono in responseObj

Spring WebFlux will only resolve top level Publishers - it is up to you to create such a pipeline.

In your case, you should have something like:

Mono<User> user = …
Mono<ResponseEntity> response = user.map(u -> new ResponseEntity(new HttpResponse(…, u));
return response;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM