連線 Azure Cosmos DB 資料庫至 Azure Spring Apps 中的應用程式

注意

Azure Spring Apps 是 Azure Spring Cloud 服務的新名稱。 雖然服務有新的名稱,但在我們努力更新資產,例如螢幕快照、影片和圖表時,您會在某些地方看到舊名稱一段時間。

本文適用於: ✔️ Java ✔️ C#

本文適用於: ✔️基本/標準✔️企業

您可以使用 Azure Spring Apps 自動將選取的 Azure 服務連線到您的應用程式,而不是手動設定 Spring Boot 應用程式。 本文示範如何將應用程式連線到 Azure Cosmos DB 資料庫。

必要條件

準備您的專案

  1. 將下列其中一個相依性新增至應用程式的 pom.xml 檔案。 選擇適合您 API 類型的相依性。

    • API 類型:NoSQL

      <dependency>
          <groupId>com.azure.spring</groupId>
          <artifactId>spring-cloud-azure-starter-data-cosmos</artifactId>
      </dependency>
      
    • API 類型:MongoDB

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-mongodb</artifactId>
      </dependency>
      
    • API 類型:Cassandra

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-cassandra</artifactId>
      </dependency>
      
  2. 執行 az spring app deploy來更新目前的應用程式,或執行 az spring app deployment create來建立此變更的新部署。

將您的應用程式 連線 至 Azure Cosmos DB

注意

根據預設,服務 連線 器會在應用層級建立。 若要覆寫連線,您可以在部署中再次建立其他連線。

使用 Azure CLI

使用 Azure CLI 來設定 Spring 應用程式,以使用 az spring connection create 命令連線到 Cosmos No SQL 資料庫,如下列範例所示。 請務必將範例中的變數取代為實際值。

注意

更新 Azure Cosmos DB 資料庫設定可能需要幾分鐘的時間才能完成。

注意

如果您使用 Cosmos Cassandra 請使用 --key_space 而非 --database。 如果您使用 Cosmos Table, 請使用 --table 而非 --database。 如需詳細資訊,請參閱 快速入門:使用 Azure CLI 在 Azure Spring Apps 中建立服務連線。

az spring connection create cosmos-sql \
    --resource-group $AZURE_SPRING_APPS_RESOURCE_GROUP \
    --service $AZURE_SPRING_APPS_SERVICE_INSTANCE_NAME \
    --app $APP_NAME \
    --target-resource-group $COSMOSDB_RESOURCE_GROUP \
    --account $COSMOSDB_ACCOUNT_NAME \
    --database $DATABASE_NAME \
    --secret

注意

如果您是第一次使用 Service 連線 or,請從執行 命令az provider register --namespace Microsoft.ServiceLinker來註冊 Service 連線 or 資源提供者開始。

提示

執行 命令 az spring connection list-support-types --output table 以取得 Azure Spring Apps 支援的目標服務和驗證方法清單。 az spring如果系統無法辨識命令,請執行 az extension add --name spring來檢查您是否已安裝必要的擴充功能。

使用 Azure 入口網站

或者,您可以完成下列步驟,使用 Azure 入口網站 來設定此連線。 Azure 入口網站 提供與 Azure CLI 相同的功能,並提供互動式體驗。

  1. 在 Azure 入口網站 中選取您的 Azure Spring Apps 實例,然後從導覽功能表中選取 [應用程式]。 選擇您要連線的應用程式,然後選取導覽功能表上的服務 連線 or

  2. 選取 建立

  3. 在 [ 基本] 索引 標籤上,針對服務類型,選取 [Cosmos DB],然後選擇訂用帳戶。 針對 [API 類型],選取 [核心][SQL]、選擇 [Cosmos DB 帳戶] 和 [資料庫]。 針對客戶端類型,選取 [Java],然後選取 [ 下一步:驗證]。 如果您尚未建立資料庫,請參閱快速入門:從 Azure 入口網站 建立 Azure Cosmos DB 帳戶、資料庫、容器和專案。

  4. 在 [驗證] 索引標籤上,選擇 [連線 ion 字串]。 服務 連線 或會自動從Cosmos DB帳戶擷取存取密鑰。 選取 [下一步:網路]

  5. 在 [網络] 索引標籤上,選取 [設定防火牆規則] 以啟用目標服務的存取權,然後選取 [下一步:檢閱 + 建立]。

  6. 在 [ 檢閱 + 建立] 索引標籤上,等候驗證通過,然後選取 [ 建立]。 建立可能需要幾分鐘的時間才能完成。

  7. 一旦產生 Spring 應用程式和 Cosmos DB 資料庫之間的連線之後,您可以在 [服務 連線 or] 頁面中看到它,然後選取展開按鈕來檢視已設定的連接變數。

下一步

在本文中,您已瞭解如何將 Azure Spring Apps 中的應用程式連線到 Azure Cosmos DB 資料庫。 若要深入瞭解如何將服務連線到您的應用程式,請參閱 連線 至 Azure Cache for Redis 快取。