azure - 使用java驱动程序异步写入documentdb

标签 azure asynchronous azure-cosmosdb azure-java-sdk

我正在使用 java-sdk 将文档插入到 cosmosdb 中。从驱动程序中我找不到任何 java api 来执行异步插入,但是我看到了 .Net api 的选项,

有没有办法(本地)在后台插入文档而不让客户端等待。

最佳答案

我查看了Azure DocumentDB SDK for Java的javadocs和源代码,不幸的是,没有任何 native 方法来支持异步操作。因此,如果您必须需要异步功能,有以下两种解决方法。

  1. 使用异步http客户端调用Cosmos REST APIs ,如OkHttp .
  2. Azure DocumentDB支持MongoDB协议(protocol),所以我认为可以使用MongoDB Async Java Driver满足您的需求,但由于官方 MongoDB Async Java Driver 似乎不支持 Azure DocumentDB,所以我失败了。然而,有一个第三方MongoDB异步Java驱动程序mongodb-async-driver ,我尝试使用MongoDB协议(protocol)成功连接到Azure DocumentDB,但是它的API与MongoDB官方的不同。

    作为引用,这是我使用第三方驱动程序的示例代码,可以下载here ,没有 Maven 仓库。

    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Future;
    
    import com.allanbank.mongodb.MongoClient;
    import com.allanbank.mongodb.MongoCollection;
    import com.allanbank.mongodb.MongoDatabase;
    import com.allanbank.mongodb.MongoFactory;
    import com.allanbank.mongodb.MongoIterator;
    import com.allanbank.mongodb.bson.Document;
    import com.allanbank.mongodb.builder.Find;
    
    public class Test {
    
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            String connectionString = "mongodb://<user>:<password>@<documentdb-name>.documents.azure.com:10255/?ssl=true&replicaSet=globaldb";
            MongoClient mongo = MongoFactory.createClient(connectionString);
            String dbName = "testdb";
            MongoDatabase database = mongo.getDatabase(dbName);
            String collName = "test";
            MongoCollection collection = database.getCollection(collName);
            Future<Long> future = collection.countAsync();
            System.out.printf("There are %,d documents in the collection.%n", future.get());
            MongoIterator iter = collection.find(Find.builder().build());
            while (iter.hasNext()) {
                System.out.println(((Document) iter.next()));
            }
        }
    
    }
    

希望有帮助。

关于azure - 使用java驱动程序异步写入documentdb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435423/

相关文章:

ios - 在 SWIFT 的 uiimage 数组中异步加载图像的问题

javascript - Promise.race 在第一次履行后是否会拒绝其他 promise ?

javascript - 使用 JavaScript 根据设备屏幕尺寸有条件地加载广告代码

c# - 如何模拟 StoredProcedureResponse

azure - 宇宙点读

azure - 如何在 Cosmos DB 中查找重复文档

.net - Azure Web应用程序超出最大请求长度

php - Google Cloud SQL - MySQL 服务器已消失

azure - Windows Azure VPN 功能

azure - 在 COSMOS 中投影表并将其与 "Not In"子句一起使用