快速入門:適用於 Java 的 Azure Cosmos DB for NoSQL 程式庫

適用於:NoSQL

開始使用適用於 Java 的 Azure Cosmos DB for NoSQL 用戶端程式庫,查詢容器中的資料,並對各個項目執行常見作業。 請依照以下步驟,使用 Azure Developer CLI 將基本解決方案部署到您的環境。

API 參考文件 | 程式庫原始程式碼 | 封裝 (Maven) | Azure Developer CLI

必要條件

設定

將這個專案的開發容器部署到您的環境。 然後使用 Azure Developer CLI (azd) 來建立 Azure Cosmos DB for NoSQL 帳戶,並部署容器化應用程式範例。 應用程式範例使用用戶端程式庫管理、建立、讀取和查詢樣本資料。

在 GitHub Codespaces 中開啟

在開發容器中開啟

重要

GitHub 帳戶的免費權利包括儲存體和核心時數。 如需詳細資訊,請參閱 GitHub 帳戶包含的儲存體和核心時數

  1. 在專案的根目錄中開啟終端。

  2. 使用 azd auth login 以向 Azure Developer CLI 進行驗證。 依照工具指定的步驟,使用您慣用的 Azure 認證向 CLI 進行驗證。

    azd auth login
    
  3. 使用 azd init 來初始化專案。

    azd init
    
  4. 在初始化期間,請設定唯一的環境名稱。

    提示

    環境名稱也將是目標資源群組名稱。 在這個快速入門中,請考慮使用 msdocs-cosmos-db-

  5. 使用 azd up部署 Azure Cosmos DB 帳戶。 Bicep 範本也會部署範例 Web 應用程式。

    azd up
    
  6. 在佈建流程期間,請選取您的訂用帳戶和所需位置。 等候佈建程序完成。 此流程「大約需要五分鐘」的時間。

  7. Azure 資源佈建完成後,輸出將包含正在執行的 Web 應用程式的 URL。

    Deploying services (azd deploy)
    
      (✓) Done: Deploying service web
    - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io>
    
    SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
    
  8. 請使用主控台中的 URL,以在瀏覽器中導覽至您的 Web 應用程式。 觀察執行中應用程式的輸出。

    執行中 Web 應用程式的螢幕快照。

安裝用戶端程式庫

用戶端程式庫可透過 Maven 以 azure-spring-data-cosmos 封裝形式提供。

  1. 瀏覽到 /src/web 資料夾,然後開啟 pom.xml 檔案。

  2. 如果封裝尚不存在,請新增 azure-spring-data-cosmos 封裝的項目。

    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-spring-data-cosmos</artifactId>
    </dependency>
    
  3. 此外如果 azure-identity 封裝不存在,請新增另一個相依性。

    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-identity</artifactId>
    </dependency>
    

物件模型

名稱 描述
EnableCosmosRepositories 這個型別是一種方法裝飾項目,用於設定存放庫以存取 Azure Cosmos DB for NoSQL。
CosmosRepository 這個類別是主要用戶端類別,用於管理容器內的資料。
CosmosClientBuilder 這個類別是個中心,用於建立存放庫所用的用戶端。
Query 這個型別是一種方法裝飾項目,用於指定存放庫執行的查詢。

程式碼範例

範本中的程式碼範例使用 cosmicworks 資料庫和 products 容器。 products 容器包含每個產品的名稱、類別、數量、唯一識別碼和銷售旗標這類詳細資料。 容器使用 /category 屬性作為邏輯分割區索引鍵。

驗證用戶端

大多數 Azure 服務的應用程式要求都需要您授權。 使用 DefaultAzureCredential 型別作為慣用方式,以實作應用程式與 Azure Cosmos DB for NoSQL 之間的無密碼連線。 DefaultAzureCredential 支援多個驗證方法,並在執行階段判斷應該使用哪個方法。

重要

您也可以直接使用密碼、連接字串或其他認證,來授權 Azure 服務要求。 不過,應該謹慎使用此方法。 開發人員應盡力不讓祕密在不安全的位置曝光。 任何取得密碼或祕密金鑰存取權的人員,都可以對資料庫伺服器進行驗證。 DefaultAzureCredential 提供更新版管理和安全性,比帳戶金鑰更具優勢,可進行無密碼驗證,完全沒有儲存金鑰需面臨的風險。

首先這個樣本會建立繼承自 AbstractCosmosConfiguration 的新類別,以設定與 Azure Cosmos DB for NoSQL 的連接。

@Configuration
@EnableCosmosRepositories
public class CosmosConfiguration extends AbstractCosmosConfiguration {

在設定類別中,這個樣本會建立 CosmosClientBuilder 類別的新執行個體,並使用 DefaultAzureCredential 執行個體來設定驗證。

@Bean
public CosmosClientBuilder getCosmosClientBuilder() {
    DefaultAzureCredential azureTokenCredential = new DefaultAzureCredentialBuilder()
        .build();
        
    return new CosmosClientBuilder()
        .endpoint(uri)
        .credential(azureTokenCredential);
}

取得資料庫

在設定類別中,樣本實作了一個方法,傳回現有資料庫 cosmicworks 的名稱。

@Override
protected String getDatabaseName() {
    return "cosmicworks";
}

取得容器

使用 Container 方法裝飾項目,設定一個類別來表示容器中的項目。 編寫類別,將所有要序列化成 JSON 的成員包含在內。 在這個範例中,該型別有唯一識別碼,以及類別、名稱、數量、價格和權限欄位。

@Container(containerName = "products", autoCreateContainer = false)
public class Item {
    private String id;
    private String name;
    private Integer quantity;
    private Boolean sale;

    @PartitionKey
    private String category;

建立項目

使用 repository.save 在容器中建立一個項目。

Item item = new Item(
    "70b63682-b93a-4c77-aad2-65501347265f",
    "gear-surf-surfboards",
    "Yamba Surfboard",
    12,
    false
);
Item created_item = repository.save(item);

讀取項目

使用唯一識別碼 (id) 和分割區索引鍵欄位,來執行點讀取作業。 使用 repository.findById 有效率地擷取特定項目。

PartitionKey partitionKey = new PartitionKey("gear-surf-surfboards");
Optional<Item> existing_item = repository.findById("70b63682-b93a-4c77-aad2-65501347265f", partitionKey);
if (existing_item.isPresent()) {
    // Do something  
}

查詢項目

在存放庫介面中定義查詢,即可對容器中的多個項目執行查詢。 這個樣本使用 Query 方法裝飾項目,定義執行此參數化查詢的方法:

SELECT * FROM products p WHERE p.category = @category
@Repository
public interface ItemRepository extends CosmosRepository<Item, String> {
    @Query("SELECT * FROM products p WHERE p.category = @category")
    List<Item> getItemsByCategory(@Param("category") String category);
}

使用 repository.getItemsByCategory 擷取查詢的所有結果。 重複查看查詢的結果。

List<Item> items = repository.getItemsByCategory("gear-surf-surfboards");
for (Item item : items) {
    // Do something
}

後續步驟