使用 Spring Data 搭配支援 MongoDB 的 Azure Cosmos DB API

本文說明如何使用 Azure Cosmos DB for MongoDB 建立一個使用 Spring Data 來儲存和檢索資訊的範例應用程式。

先決條件

  • Git 用戶端。

建立 Azure Cosmos DB 帳戶

用 Azure portal 建立 Azure Cosmos DB 帳戶

注意

欲了解更多關於建立帳號的資訊,請參閱 Azure Cosmos DB 文件

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

  2. 選擇建立資源,選擇資料庫,然後選擇 Azure Cosmos DB

  3. 在 [選取 API 選項] 畫面上,選取 [Azure Cosmos DB for MongoDB]。

    Azure 入口網站中 [Select API] 選項畫面的螢幕擷取畫面,其中已選取 Azure Cosmos DB for MongoDB。

  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. https://portal.azure.com/ 流覽至 Azure 入口網站並登入。

  2. 點選「所有資源」,然後選擇你建立的 Azure Cosmos DB 帳號。

  3. 點選 「連線字串」,並複製「 主要連線字串 」欄位的值。 之後用這個值來設定你的應用程式。

    Connection 字串頁面的截圖,顯示 Azure Cosmos DB 帳號的主要連線字串。

設定範例應用程式

  1. 打開一個指令殼,並用 git 指令複製範例專案。 例如:

    git clone https://github.com/spring-guides/gs-accessing-data-mongodb.git
    
  2. 在範例專案的 root>/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']
    

總結

在這個教學中,你創建了一個範例 Java 應用程式,使用 Spring Data 來儲存和檢索資訊,方法是使用 Azure Cosmos DB for MongoDB。

清除資源

當你不再需要資源時,使用 Azure 入口網站刪除它們。 刪除資源有助於避免意外收費。

後續步驟

若要深入瞭解 Spring 和 Azure,請繼續前往 Azure 上的 Spring 檔中心。

另請參閱

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