在本指南中,你將開發一個 Java 主控台應用程式,以連接 Azure DocumentDB 叢集。 本指南包含設定開發環境、使用 azure-identity 適用於 Java 的 Azure SDK 套件進行驗證,以及與資料庫和集合互動以管理檔的步驟。
先決條件
Azure 訂用帳戶
- 如果您沒有 Azure 訂用帳戶,請建立 免費帳戶
一個現有的 Azure DocumentDB 叢集
- 如果你沒有叢集,就建立 一個新的叢集
使用 Azure Cloud Shell 中的 Bash 環境。 如需詳細資訊,請參閱開始使用 Azure Cloud Shell。
若要在本地執行 CLI 參考命令,請安裝 Azure CLI。 若您在 Windows 或 macOS 上執行,請考慮在 Docker 容器中執行 Azure CLI。 如需詳細資訊,請參閱 如何在 Docker 容器中執行 Azure CLI。
如果您使用的是本機安裝,請使用 az login 命令,透過 Azure CLI 來登入。 請遵循您終端機上顯示的步驟,完成驗證程序。 如需其他登入選項,請參閱 使用 Azure CLI 向 Azure 進行驗證。
出現提示時,請在第一次使用時安裝 Azure CLI 延伸模組。 如需擴充功能的詳細資訊,請參閱 使用和管理 Azure CLI 的擴充功能。
執行 az version 以尋找已安裝的版本和相依程式庫。 若要升級至最新版本,請執行 az upgrade。
設定主控台應用程式
接下來,建立新的主控台應用程式專案,並匯入必要的函式庫來驗證您的叢集。
使用 Maven 命令行工具建立新的 Maven 專案。
mvn archetype:generate -DgroupId=com.cosmicworks -DartifactId=mongodb-console-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false流覽至項目目錄。
cd mongodb-console-app在適當的套件目錄中,建立一個包含類別的新
Main檔案。mkdir -p src/main/java/com/cosmicworks touch src/main/java/com/cosmicworks/App.java將
azure-identity相依性新增至 pom.xml 檔案。<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.15.4</version> </dependency>將
mongodb-driver-sync相依性新增至 pom.xml 檔案。<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>5.4.0</version> </dependency>
連接至叢集
現在,使用 Azure.Identity 庫取得 TokenCredential,以用來連線到您的叢集。 官方 MongoDB 驅動程式有一個特殊的介面,必須實作才能從 Microsoft Entra 取得令牌,以在連線到叢集時使用。
首先,在 Java 類別檔案頂端匯入必要的類別。
import java.util.concurrent.TimeUnit; import org.bson.Document; import org.bson.conversions.Bson; import com.azure.core.credential.TokenCredential; import com.azure.core.credential.TokenRequestContext; import com.azure.identity.DefaultAzureCredentialBuilder; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCredential; import com.mongodb.MongoCredential.OidcCallbackContext; import com.mongodb.MongoCredential.OidcCallbackResult; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.ReplaceOptions; import com.mongodb.client.result.UpdateResult;在您的主要方法中,建立
DefaultAzureCredential執行個體,並設定 OpenID Connect (OIDC) 回撥以擷取權杖。TokenCredential credential = new DefaultAzureCredentialBuilder().build(); MongoCredential.OidcCallback oidcCallback = new MongoCredential.OidcCallback() { @Override public OidcCallbackResult onRequest(OidcCallbackContext context) { TokenRequestContext tokenRequestContext = new TokenRequestContext() .addScopes("https://ossrdbms-aad.database.windows.net/.default"); String token = credential.getTokenSync(tokenRequestContext).getToken(); return new OidcCallbackResult(token); } };使用您先前定義的回呼,創建
MongoCredential的新實例。MongoCredential mongoCredential = MongoCredential.createOidcCredential(null) .withMechanismProperty("OIDC_CALLBACK", oidcCallback);建立叢集名稱和整個主機端點的變數。
String clusterName = "<azure-documentdb-cluster-name>"; String host = clusterName + ".global.mongocluster.cosmos.azure.com";使用主機、連線最佳實務和憑證建構
MongoClientSettings實例。MongoClientSettings settings = MongoClientSettings.builder() .applyToClusterSettings(builder -> builder .srvHost(host)) .applyToSocketSettings(builder -> builder .connectTimeout(2, TimeUnit.MINUTES)) .applyToSslSettings(builder -> builder .enabled(true)) .retryWrites(true) .credential(mongoCredential) .build();使用建構設定建立新的
MongoClient。MongoClient client = MongoClients.create(settings); System.out.println("Client created");
執行一般作業
最後,使用官方程式庫處理資料庫、集合和文件的常見工作。 在這裡,您可以使用與 MongoDB 或 DocumentDB 互動的相同類別和方法來管理您的集合和專案。
取得
database和collection的參考。MongoDatabase database = client.getDatabase("<database-name>"); System.out.println("Database pointer created"); MongoCollection<Document> collection = database.getCollection("<collection-name>"); System.out.println("Collection pointer created");使用類別
Product來代表您的檔。public class Product { private String _id; private String category; private String name; private int quantity; private double price; private boolean clearance; // Getters and setters ommitted for brevity }使用
collection.replaceOne並啟用 upsert 建立新文件。Document document = new Document() .append("_id", "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb") .append("category", "gear-surf-surfboards") .append("name", "Yamba Surfboard") .append("quantity", 12) .append("price", 850.00) .append("clearance", false); Bson match = Filters.eq("_id", "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"); ReplaceOptions options = new ReplaceOptions().upsert(true); UpdateResult result = collection.replaceOne(match, document, options); System.out.println("Document upserted with _id:\\t" + result.getUpsertedId().asString().getValue());使用
collection.find和唯一標識碼執行單一檔的查閱。Bson filter = Filters.eq("_id", "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"); collection.find(filter).forEach(doc -> { System.out.println("Read document _id:\\t" + doc.toJson()); });使用二進位 JSON (BSON) 篩選來執行一般查詢。
Bson query = Filters.eq("category", "gear-surf-surfboards"); collection.find(query).forEach(doc -> { System.out.println("Found document:\\t" + doc.toJson()); });使用篩選和
collection.deleteMany刪除檔。Bson filter = Filters.eq("clearance", true); collection.deleteMany(filter);