Returns 来自 Spring 5 WebFlux 中 RouterFunction 处理程序的对象

Returns a object from RouterFunction handlers in Spring 5 WebFlux

我有以下 RouterFunction 的 bean 定义:

@Bean
    RouterFunction<?> routes(DestinationHandler destinationHandler) {

        return nest(path("/destination"), route(method(GET), destinationHandler::findAll));

    }

这是处理函数:

public Mono<ServerResponse> findAll(ServerRequest request) {
    Flux<Destination> destinations = destinationService.findAll();

    ResponseData responseData = buildResponseData(destinations);

    return ok().body(Mono.just(responseData), ResponseData.class);

}

private ResponseData buildResponseData(Flux<Destination> destinations) {
    ResponseData responseData = new ResponseData();
    responseData.setStatus(HttpStatus.OK.value());
    responseData.setCode(DESTINATION_LIST_SUCCESS_CODE);
    responseData.setMessage(DESTINATION_LIST_SUCCESS_MESSAGE);
    responseData.setData(destinations);
    return responseData;
}

我的响应数据:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseData {
    private int status;
    private String code;
    private String message;
    private Object data;
}

目的地class:

//lombok annotations
public class Destination {
    private int id;
    private String local;
}

结果为:

{
"status":200, "code":"destination_list_success", "message":"Retorno realizado com sucesso", "data":{
"scanAvailable":是的, "prefetch":-1 } }

我怎样才能return正确的目的地列表?

试试这个

private ResponseData buildResponseData(Flux<Destination> destinations) 
{
    ResponseData responseData = new ResponseData();
    responseData.setStatus(HttpStatus.OK.value());
    responseData.setCode(DESTINATION_LIST_SUCCESS_CODE);
    responseData.setMessage(DESTINATION_LIST_SUCCESS_MESSAGE);
    responseData.setData(destinations.block());
    return responseData;
}

并将 ResponseData class 更改为

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseData {
    private int status;
    private String code;
    private String message;
    private List<...> data;
}

为此,您需要将 Flux<Destination> 转换为 Mono<List<Destination>>,因此请进行以下更改:

buildResponseData(Flux<Destination> destinations)

至:

buildResponseData(List<Destination> destinations)

并将 return 块更改为:

return ok().body(destinations.collectList().map(d-> buildResponseData(d)), ResponseData.class);

你应该翻转顺序。按照 Carlos 的回答:

return destinations.collectList().map(d-> ok().body(buildResponseData(d)));