我有一个 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
被调用以提供返回值(应该 complete
在 get
之前被调用,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.complete
在finally {
block 以确保结果始终得到解决,即使在回调期间出现意外错误也是如此。
关于java - Mongodb 异步 java 驱动程序 find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33257459/