搭配適用於 MongoDB 的 Azure Cosmos DB API 使用 Spring Data

本文示範如何使用適用於 MongoDB 的 Azure Cosmos DB 來儲存和擷取資訊的範例應用程式

必要條件

  • Git 用戶端。

建立 Azure Cosmos DB 帳戶

使用 Azure 入口網站建立 Azure Cosmos DB 帳戶

注意

您可以在 Azure Cosmos DB 檔中閱讀有關建立帳戶的詳細資訊。

  1. 流覽至 Azure 入口網站,https://portal.azure.com/然後登入。

  2. 選取 [建立資源],然後選取 [資料庫],然後選取 [Azure Cosmos DB]。

  3. 在 [ 選取 API] 選項 畫面上,選取 [適用於 MongoDB 的 Azure Cosmos DB]。

    Azure 入口網站,建立資源,選取 [API] 選項,選取 [適用於 MongoDB 的 Azure Cosmos DB]。

  4. 指定下列資訊:

    • 用帳戶:指定要使用的 Azure 訂用帳戶。
    • 資源群組:指定是要建立新的資源群組,還是選擇現有的資源群組。
    • 帳戶名稱:為您的 Azure Cosmos DB 帳戶選擇唯一名稱;這會用來建立完整功能變數名稱,例如 wingtiptoysmongodb.documents.azure.com
    • API:指定 Azure Cosmos DB for MongoDB API 本教學課程。
    • 位置:指定資料庫最接近的地理區域。
  5. 輸入上述所有資訊后,按兩下 [ 檢閱 + 建立]。

  6. 如果檢閱頁面上的所有項目看起來都正確,請按兩下 [ 建立]。

    檢閱您的 Azure Cosmos DB 帳戶設定。

擷取 Azure Cosmos DB 帳戶的 連接字串

  1. 流覽至 Azure 入口網站 ,https://portal.azure.com/然後登入。

  2. 按兩下 [所有資源],然後按下您剛才建立的 Azure Cosmos DB 帳戶。

  3. 按兩下 [連線 ion 字串],然後複製 [主要 連線 ion String] 字段的值;您稍後會使用該值來設定應用程式。

    擷取 Azure Cosmos DB 連接字串。

設定範例應用程式

  1. 開啟命令殼層,並使用 git 命令複製範例專案,如下列範例所示:

    git clone https://github.com/spring-guides/gs-accessing-data-mongodb.git
    
  2. 在<範例專案的專案根>目錄/complete/src/main 目錄中建立資源目錄,然後在 resources 目錄中建立 application.properties 檔案

  3. 文本編輯器中開啟 application.properties 檔案,並在檔案中新增下列幾行,並將範例值取代為先前的適當值:

    spring.data.mongodb.database=wingtiptoysmongodb
    spring.data.mongodb.uri=mongodb://wingtiptoysmongodb:AbCdEfGhIjKlMnOpQrStUvWxYz==@wingtiptoysmongodb.documents.azure.com:10255/?ssl=true&replicaSet=globaldb
    

    其中:

    參數 描述
    spring.data.mongodb.database 指定本文稍早的 Azure Cosmos DB 帳戶名稱。
    spring.data.mongodb.uri 指定本文稍早的主要 連線 字串
  4. 儲存並關閉 application.properties 檔案。

封裝和測試應用程式範例

若要建置應用程式,請流覽至目錄 /gs-accessing-data-mongodb/complete,其中包含 pom.xml 檔案。

  1. 使用 Maven 建置範例應用程式,並設定 Maven 略過測試;例如:

    mvn clean package -DskipTests
    
  2. 啟動應用程式範例;例如:

    
    java -jar target/accessing-data-mongodb-complete-0.0.1-SNAPSHOT.jar
    

    應用程式應該會傳回如下所示的值:

    Customers found with findAll():
    -------------------------------
    Customer[id=5c1b4ae4d0b5080ac105cc13, firstName='Alice', lastName='Smith']
    Customer[id=5c1b4ae4d0b5080ac105cc14, firstName='Bob', lastName='Smith']
    
    Customer found with findByFirstName('Alice'):
    --------------------------------
    Customer[id=5c1b4ae4d0b5080ac105cc13, firstName='Alice', lastName='Smith']
    Customers found with findByLastName('Smith'):
    --------------------------------
    Customer[id=5c1b4ae4d0b5080ac105cc13, firstName='Alice', lastName='Smith']
    Customer[id=5c1b4ae4d0b5080ac105cc14, firstName='Bob', lastName='Smith']
    

摘要

在本教學課程中,您已建立使用 Spring Data 來儲存及擷取使用適用於 MongoDB 的 Azure Cosmos DB 資訊的範例 Java 應用程式。

清除資源

不再需要時,請使用 Azure 入口網站 來刪除本文中建立的資源,以避免產生非預期的費用。

下一步

若要深入了解 Spring 和 Azure,請繼續閱讀「Azure 上的 Spring」文件中心中的資訊。

另請參閱

如需如何搭配使用 Azure 和 Java 的詳細資訊,請參閱適用於 Java 開發人員的 Azure使用 Azure DevOps 和 Java