![](/img/trans.png)
[英]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.