在使用一个对象列表时用Flux
public Mono<ServerResponse> listPeople(ServerRequest request) {
Flux<Person> people = repository.allPeople();
return ok().contentType(APPLICATION_JSON).body(people, Person.class);
}
但是当需要返回一个自定义的json数据时,就需要把Flux
转换成Mono
,使用collectList()
转换为一个对象列表,代码如下:
public Mono<ServerResponse> getTitle(ServerRequest request) {
Mono<List<Title>> titleList = feignService.getTitle().collectList();
return titleList.map(data -> ReactiveResponse.builder()
.message(Message.SUCCESS)
.status(HttpStatus.SUCCESS)
.data(data)
.build()
).flatMap(data -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.bodyValue(data));
}