如何将 List<String> 转换为 Mono<List>
How to convert List<String> into a Mono<List>
我正在尝试将此方法转换为反应式方法
@GetMapping(RestConstants.BASE_PATH_AUDIENCE + "/link")
public List<String> users () {
List<String> list= new ArrayList<>();
MongoCollection mongoCollection = mongoTemplate.getCollection("collection");
DistinctIterable distinctIterable = mongoCollection.distinct("user_name", String.class);
MongoCursor mongoCursor = distinctIterable.iterator();
while (mongoCursor.hasNext()){
String user = (String)mongoCursor.next();
creatorsList.add(user);
}
return list;
}
我有类似的东西,但我不知道如何将 ArrayList 转换为 return 一个 Mono
@GetMapping(RestConstants.BASE_PATH_AUDIENCE + "/link")
public Mono<List<String>> usersReactive () {
List<Mono<String>> list= new ArrayList<List>();
MongoCollection mongoCollection = mongoTemplate.getCollection("collection");
DistinctIterable distinctIterable = mongoCollection.distinct("user_name", String.class);
MongoCursor mongoCursor = distinctIterable.iterator();
while (mongoCursor.hasNext()){
String user = (String)mongoCursor.next();
list.add(user);
}
return list;
}
如果你真的想要一个 Mono,那么 只需 将你想要传输的值包装在其中:
return Mono.just(creatorsList);
但我怀疑您是否真的想要 return Mono 中的列表。通常,反应性端点 returning 多个项目会 return 一个 Flux
return Flux.fromIterable(creatorsList);
但是由于您的 MongoCursor
已经是可迭代的(您在增强的 for-loop 中使用它的迭代器),您可以将光标直接流式传输到 flux。这使您无需先将所有项目收集到列表中。
return Flux.fromIterable(cursor);
最后,如果您尝试将应用程序转换为反应式应用程序,明智的做法是使用 Mongo 驱动程序,该驱动程序具有对反应式流的本机支持:https://docs.mongodb.com/drivers/reactive-streams/
我正在尝试将此方法转换为反应式方法
@GetMapping(RestConstants.BASE_PATH_AUDIENCE + "/link")
public List<String> users () {
List<String> list= new ArrayList<>();
MongoCollection mongoCollection = mongoTemplate.getCollection("collection");
DistinctIterable distinctIterable = mongoCollection.distinct("user_name", String.class);
MongoCursor mongoCursor = distinctIterable.iterator();
while (mongoCursor.hasNext()){
String user = (String)mongoCursor.next();
creatorsList.add(user);
}
return list;
}
我有类似的东西,但我不知道如何将 ArrayList 转换为 return 一个 Mono
@GetMapping(RestConstants.BASE_PATH_AUDIENCE + "/link")
public Mono<List<String>> usersReactive () {
List<Mono<String>> list= new ArrayList<List>();
MongoCollection mongoCollection = mongoTemplate.getCollection("collection");
DistinctIterable distinctIterable = mongoCollection.distinct("user_name", String.class);
MongoCursor mongoCursor = distinctIterable.iterator();
while (mongoCursor.hasNext()){
String user = (String)mongoCursor.next();
list.add(user);
}
return list;
}
如果你真的想要一个 Mono,那么 只需 将你想要传输的值包装在其中:
return Mono.just(creatorsList);
但我怀疑您是否真的想要 return Mono 中的列表。通常,反应性端点 returning 多个项目会 return 一个 Flux
return Flux.fromIterable(creatorsList);
但是由于您的 MongoCursor
已经是可迭代的(您在增强的 for-loop 中使用它的迭代器),您可以将光标直接流式传输到 flux。这使您无需先将所有项目收集到列表中。
return Flux.fromIterable(cursor);
最后,如果您尝试将应用程序转换为反应式应用程序,明智的做法是使用 Mongo 驱动程序,该驱动程序具有对反应式流的本机支持:https://docs.mongodb.com/drivers/reactive-streams/