如何返回 Mono<ServerResponse>
Posted
技术标签:
【中文标题】如何返回 Mono<ServerResponse>【英文标题】:How to return Mono<ServerResponse> 【发布时间】:2021-09-09 22:24:42 【问题描述】:请参阅下面代码的 cmets 部分中嵌入的我的问题 -
// This should return a list of all ids and their name and status info, e.g. as json
public Mono<ServerResponse> f1(String originalId)
// this gives list of ids which are comma separated
Mono<String> ids = f2(originalId);
ids.flatMapIterable(line -> Arrays.asList(line.split(COMMA)))
.doOnNext(id ->
Mono<String> idName = f3(id);
Mono<String> idStatus = f4(id);
Mono<Tuple2<String, String>> combined = Mono.zip(idName, idStatus);
// How do i return all the combined Mono tuples as Mono<ServerResponse>
).subscribe();
// Need to return proper Mono - not empty
return Mono.empty();
我也不确定是否应该返回 Flux 或 Mono 作为 f1() 的返回类型作为它的 id 列表及其各自的值
【问题讨论】:
【参考方案1】:您需要返回Mono<ServerResponse>
。
public Mono<ServerResponse> f1(String key)
Mono<String> ids = f2(key);
Flux<IdInfo> idInfoFlux = ids.flatMapIterable(line -> Arrays.asList(line.split(",")))
.flatMap(id ->
Mono<String> idName = getIdName(id);
Mono<String> idStatus = getIdStatus(id);
return Mono.zip(idName, idStatus, (name, status) -> new IdInfo(name, status));
)
.doOnNext(id -> System.out.println(id));
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(idInfoFlux, IdInfo.class);
// your DTO class that you would like to pass in response as json
public static class IdInfo
String idName;
String idStatus;
public IdInfo(String idName, String idStatus)
this.idName = idName;
this.idStatus = idStatus;
public String toString()
return String.format("IdInfo [idName=%s, idStatus=%s]", idName, idStatus);
【讨论】:
以上是关于如何返回 Mono<ServerResponse>的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Spring Webflux 中返回 Mono<Map<String, Flux<Integer>>> 响应?