我有一个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。在这种情况下,您可以使用class 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的-method还具有替代方法,其重载带有timeout参数。我建议使用它来防止由于某种原因未调用回调时程序累积挂起的线程。在一个try {
块中实现整个回调并result.complete
在该finally {
块中执行以确保结果总是得到解决也是一个好主意,即使在回调过程中发生意外错误时也是如此。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句