java 如何使用webclient将Mono转换< PojoResponseObject>为Mono< ResponseEntity>

wgeznvg7  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(250)

我有以下webclient调用

public Mono<String> sendFile(final MultipartFile multipartFile) {
    Mono<Response> response = webClient.post()
                .uri(new URI("someurl"))
                .body(BodyInserters.fromMultipartData(multiValueMap))
                .retrieve()
                .bodyToMono(Response.class);

    // Need to implement additional logic here to convert the Mono<Response> into Mono<RequestID>

}

public class Response {

    private RequestID requestID;

}

public class RequestID {

    private String requestID;

}

对API的调用返回到JSON Response POJO对象中,但是我只对RequestID POJO中的requestID感兴趣,所以我想将我的Mono转换< Response >为Mono< RequestId >,但不知道如何做到这一点?
所以对于我的控制器,我基本上想要类似于这样的东西:

@PostMapping("/request")
    public Mono<ResponseEntity> sendRequest(@RequestPart(value = "file") final MultipartFile multipartFile) {
        Mono<RequestID> request =  service.sendFile(multipartFile);
        Response2<String> response = new Response<>(request.getRequestID, true, "SUCCESS"); // Response2 is just a POJO with three fields
        return new Mono<ResponseEntity<>>(response, HttpStatus.CREATED);
    }
mf98qq94

mf98qq941#

您必须使用map将Mono发出的数据转换为另一个Mono
通过对Mono应用同步函数来转换它发出的项。
所以逻辑就是

public Mono<String> sendFile(final MultipartFile multipartFile) {
Mono<Response> response = webClient.post()
            .uri(new URI("someurl"))
            .body(BodyInserters.fromMultipartData(multiValueMap))
            .retrieve()
            .bodyToMono(Response.class)
            .map(data->data.getRequestID().getRequestID());

  return response;

}

在控制器中也使用map方法进行数据转换成Mono<ResponseEntity>

@PostMapping("/request")
public Mono<ResponseEntity> sendRequest(@RequestPart(value = "file") final MultipartFile multipartFile) {
    Mono<RequestID> request =  service.sendFile(multipartFile);
    
    return request.map(id->ResponseEntity.body(new Response<>(id, true, "SUCCESS")).status(HttpStatus.CREATED)));
}

相关问题