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

目的地舱位:

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

这导致:


{ "状态":200, "代码":"destination_list_success", "消息":"Retorno realizado com sucesso", "数据":{
"scanAvailable":true, "预取":-1 }}

如何返回正确的目的地列表?

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

buildResponseData(Flux<Destination> destinations)

自:

buildResponseData(List<Destination> destinations)

并将返回块更改为:

return ok().body(destinations.collectList().map(d-> buildResponseData(d)), 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.block());
    return responseData;
}

并将响应数据类更改为

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

你应该翻转顺序。按照卡洛斯的回答:

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

相关内容

  • 没有找到相关文章

最新更新