[英]MongoDB Java Driver: MongoCore Driver vs. MongoDB Driver vs. MongoDB Async Driver
[英]Mongodb async java driver find()
我有一个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
will会阻塞,直到调用complete
来提供返回值为止(应该在get
之前调用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
}
CompletableFuture的get()
方法还有一个带有超时参数的替代重载 。 我建议使用它来防止由于某种原因未调用回调时程序累积挂起的线程。 最好在try {
块中实现整个回调,并在finally {
块中执行result.complete
,以确保即使在回调期间发生意外错误的情况下,结果也始终得到解决,这也是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.