【问题标题】:How to convert List<String> into a Mono<List>如何将 List<String> 转换为 Mono<List>
【发布时间】:2022-01-27 21:18:32
【问题描述】:

我正在尝试将此方法转换为响应式方法

@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 以返回 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;
}

【问题讨论】:

标签: java spring reactive-programming spring-webflux


【解决方案1】:

如果你真的想要一个 Mono,那么 只需 将你想在其中传输的值包装起来:

return Mono.just(creatorsList);

但我怀疑你真的想在 Mono 中返回一个列表。通常,返回多个项目的响应式端点将返回 Flux

return Flux.fromIterable(creatorsList);

但是由于您的 MongoCursor 已经是可迭代的(您在增强的 for 循环中使用它的迭代器),您可以将光标直接流式传输到通量。这样您就不必先将所有项目收集到一个列表中。

return Flux.fromIterable(cursor);

最后,如果您想将应用程序转换为响应式应用程序,明智的做法是使用具有对响应式流的本机支持的 ​​Mongo 驱动程序:https://docs.mongodb.com/drivers/reactive-streams/

【讨论】:

  • 它对我有用,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2022-01-11
  • 2017-06-19
  • 2021-07-27
  • 2019-04-13
  • 2020-01-11
  • 2013-08-26
  • 2020-11-27
  • 2021-09-17
相关资源
最近更新 更多