簡體   English   中英

MongoDB異步Java驅動程序find()

[英]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 getget立即使用提供的值返回)。

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 ,以確保即使在回調期間發生意外錯誤的情況下,結果也始終得到解決,這也是一個好主意。

你是對的。

這是Mongo異步驅動程序的正確行為(請參閱MongoIterable.into )。

但是,為什么在這種情況下不使用同步驅動程序? 有什么理由使用異步方法嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM