java - Mongodb 异步 java 驱动程序 find()

标签 java mongodb asynchronous

我有一个 Web 应用程序,我必须在其中将 mongodb find() 的结果从我的 Java 后端返回到前端。 我正在使用 Async Java 驱动程序,我认为我必须从 mongo 返回结果的唯一方法是这样的:

public String getDocuments(){
  ...
  collection.find(query).map(Document::toJson)
        .into(new HashSet<String>(), new SingleResultCallback<HashSet<String>>() {
            @Override
            public void onResult(HashSet<String> strings, Throwable throwable) {
              // here I have to get all the Json Documents in the set,
              // make a whole json string and wake the main thread
            }
        });
  // here I have to put the main thread to wait until I get the data in
  // the onResult() method so I can return the string back to the front-end
  ...
  return jsonString;
}

这个假设是正确的还是有另一种方法可以做到这一点?

最佳答案

异步 ​​API(任何基于回调的 API,不一定是 MongoDB)可以成为多线程应用程序的真正福音。但要真正从中受益,您需要以异步方式设计整个应用程序架构。这并不总是可行的,尤其是当它应该适合不是建立在回调之上的给定框架时。

所以有时(就像您的情况一样)您只想以同步方式使用异步 API。在这种情况下,您可以使用类 CompletableFuture .

此类提供(除其他外)两种方法 <T> get()complete(<T> value) .方法get将阻塞直到 complete被调用以提供返回值(应该 completeget 之前被调用,get 立即返回提供的值)。

public String getDocuments(){
  ...
  CompletableFuture<String> result = new CompletableFuture<>(); // <-- create an empty, uncompleted Future

  collection.find(query).map(Document::toJson)
        .into(new HashSet<String>(), new SingleResultCallback<HashSet<String>>() {
            @Override
            public void onResult(HashSet<String> strings, Throwable throwable) {
              // here I have to get all the Json Documents in the set and
              // make a whole json string

              result.complete(wholeJsonString); // <--resolves the future
            }
        });

  return result.get(); // <-- blocks until result.complete is called
}

get() - CompletableFuture 的方法也 has an alternative overload with a timeout parameter .我建议使用它来防止您的程序在出于任何原因未调用回调时累积挂起线程。在 try { 中实现整个回调也是一个好主意。阻止并执行 result.completefinally { block 以确保结果始终得到解决,即使在回调期间出现意外错误也是如此。

关于java - Mongodb 异步 java 驱动程序 find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33257459/

相关文章:

java - 使用 java 配置 Api

node.js - mongodb、express.js 应用部署最佳实践

非常大的数据集的 MongoDB 缩放和内存使用

swift - 在解释响应之前,如何确保该函数完成?

Java - 链表初始化不正确

java - 获取异常-java.lang.IllegalStateException : getOutputStream() has already been called for this response

java - 在 DAO 实现类中实现默认的 JPA findAll 方法

mongodb - 打印 mongoDB Collection Golang 中的所有记录

c# - 何时使用 System.Threading.ThreadPool 以及何时使用众多自定义线程池之一?

javascript - 如何/是否重写异步 :false AJAX function?