快速入門:建置 JAVA 應用程式來管理 Azure Cosmos DB Cassandra API 資料Quickstart: Build a Java app to manage Azure Cosmos DB Cassandra API data

本快速入門示範如何使用 JAVA 與 Azure Cosmos DB Cassandra API,以藉由從 GitHub 複製範例來建置設定檔應用程式。This quickstart shows how to use Java and the Azure Cosmos DB Cassandra API to build a profile app by cloning an example from GitHub. 此快速入門也會示範如何使用 Web 型 Azure 入口網站來建立 Azure Cosmos DB 帳戶。This quickstart also shows you how to use the web-based Azure portal to create an Azure Cosmos DB account.

Azure Cosmos DB 是 Microsoft 的全域分散式多模型資料庫服務。Azure Cosmos DB is Microsoft's globally distributed multi-model database service. 您可以快速建立及查詢文件、資料表、索引鍵/值及圖形資料庫,所有這些都受惠於位於 Azure Cosmos DB 核心的全域散發和水平調整功能。You can quickly create and query document, table, key-value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Azure Cosmos DB.

必要條件Prerequisites

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.或者,您可以免費試用 Azure Cosmos DB,無須 Azure 訂用帳戶,也無須任何費用和約定付款。如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin. Alternatively, you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments.

此外,您需要:In addition, you need:

  • JAVA 開發套件 (JDK) 8 版 (英文)Java Development Kit (JDK) version 8
    • 務必設定 JAVA_HOME 環境變數,以指向 JDK 安裝所在的資料夾。Be sure to set the JAVA_HOME environment variable to point to the folder where the JDK is installed.
  • 下載安裝 Maven 二進位封存檔Download and install a Maven binary archive
    • 在 Ubuntu 上,您可以執行 apt-get install maven 來安裝 Maven。On Ubuntu, you can run apt-get install maven to install Maven.
  • GitGit
    • 在 Ubuntu 上,您可以執行 sudo apt-get install git 來安裝 Git。On Ubuntu, you can run sudo apt-get install git to install Git.

建立資料庫帳戶Create a database account

您必須先使用 Azure Cosmos DB 建立 Cassandra 帳戶,才可以建立文件資料庫。Before you can create a document database, you need to create a Cassandra account with Azure Cosmos DB.

  1. 在新的瀏覽器視窗中,登入 Azure 入口網站In a new browser window, sign in to the Azure portal.

  2. 選取 [建立資源] > [資料庫] > [Azure Cosmos DB] 。Select Create a resource > Databases > Azure Cosmos DB.

    Azure 入口網站資料庫窗格

  3. 在 [建立 Azure Cosmos DB 帳戶] 頁面中,輸入新的 Azure Cosmos DB 帳戶的設定。In the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    設定Setting Value 說明Description
    訂用帳戶Subscription 您的訂用帳戶Your subscription 選取要用於此 Azure Cosmos DB 帳戶的 Azure 訂用帳戶。Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    資源群組Resource Group 新建Create new

    然後輸入識別碼中所提供的同一個唯一名稱Then enter the same unique name as provided in ID
    選取 [建立新的] 。Select Create new. 然後為您的帳戶輸入新的資源群組名稱。Then enter a new resource-group name for your account. 為求簡化,請使用和識別碼相同的名稱。For simplicity, use the same name as your ID.
    帳戶名稱Account Name 輸入唯一名稱Enter a unique name 輸入唯一名稱來識別您的 Azure Cosmos DB 帳戶。Enter a unique name to identify your Azure Cosmos DB account. 因為 documents.azure.com 會附加到您所提供的識別碼以建立 URI,請使用唯一識別碼。Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    識別碼只能使用小寫字母、數字及連字號 (-) 字元。The ID can use only lowercase letters, numbers, and the hyphen (-) character. 長度必須介於 3 到 31 個字元之間。It must be between 3 and 31 characters in length.
    APIAPI CassandraCassandra API 會決定要建立的帳戶類型。The API determines the type of account to create. Azure Cosmos DB 提供五個 API:Core(SQL) (適用於文件資料庫)、Gremlin (適用於圖形資料庫)、MongoDB (適用於文件資料庫)、「Azure 資料表」及 Cassandra。Azure Cosmos DB provides five APIs: Core(SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. 目前,您必須為每個 API 建立個別個帳戶。Currently, you must create a separate account for each API.

    選取 [Cassandra] ,因為在此快速入門中,您會建立可搭配 Cassandra API 使用的資料表。Select Cassandra because in this quickstart you are creating a table that works with the Cassandra API.

    深入了解 Cassandra APILearn more about the Cassandra API.
    位置Location 選取最接近使用者的區域Select the region closest to your users 選取用來裝載 Azure Cosmos DB 帳戶的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用最接近使用者的位置,以便他們能以最快速度存取資料。Use the location that's closest to your users to give them the fastest access to the data.

    請選取 [檢閱 + 建立] 。Select Review+Create. 您可以略過 [網路] 和 [標記] 區段。You can skip the Network and Tags section.

    Azure Cosmos DB 的新帳戶頁面

  4. 建立帳戶需要幾分鐘的時間。The account creation takes a few minutes. 等候入口網站顯示頁面「恭喜!已建立您的 Azure Cosmos DB 帳戶」。Wait for the portal to display the page saying Congratulations! Your Azure Cosmos DB account was created.

複製範例應用程式Clone the sample application

現在讓我們切換為使用程式碼。Now let's switch to working with code. 我們將從 GitHub 複製 Cassandra 應用程式、設定連接字串,然後加以執行。Let's clone a Cassandra app from GitHub, set the connection string, and run it. 您會看到,以程式設計方式來處理資料有多麼的容易。You'll see how easy it is to work with data programmatically.

  1. 開啟命令提示字元。Open a command prompt. 建立名為 git-samples 的新資料夾。Create a new folder named git-samples. 接著,關閉命令提示字元。Then, close the command prompt.

    md "C:\git-samples"
    
  2. 開啟 git 終端機視窗 (例如 git bash),並使用 cd 命令變更至要安裝範例應用程式的新資料夾。Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. 執行下列命令來複製範例存放庫。Run the following command to clone the sample repository. 此命令會在您的電腦上建立範例應用程式副本。This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-cassandra-java-getting-started.git
    

檢閱程式碼Review the code

此為選用步驟。This step is optional. 如果您有興趣了解程式碼如何建立資料庫資源,您可以檢閱下列程式碼片段。If you're interested to learn how the code creates the database resources, you can review the following snippets. 或者也可以直接跳至更新您的連接字串Otherwise, you can skip ahead to Update your connection string. 這些程式碼片段摘錄自 src/main/java/com/azure/cosmosdb/cassandra/util/CassandraUtils.java 檔案。These snippets are all taken from the src/main/java/com/azure/cosmosdb/cassandra/util/CassandraUtils.java file.

  • Cassandra 主機、連接埠、使用者名稱、密碼與 SSL 選項皆已設定。The Cassandra host, port, user name, password, and SSL options are set. 連接字串資訊來自 Azure 入口網站的連接字串頁面。The connection string information comes from the connection string page in the Azure portal.

    cluster = Cluster.builder().addContactPoint(cassandraHost).withPort(cassandraPort).withCredentials(cassandraUsername, cassandraPassword).withSSL(sslOptions).build();
    
  • cluster 會連線至 Azure Cosmos DB Cassandra API,並傳回要存取的工作階段。The cluster connects to the Azure Cosmos DB Cassandra API and returns a session to access.

    return cluster.connect();
    

下列程式碼片段摘錄自 src/main/java/com/azure/cosmosdb/cassandra/repository/UserRepository.java 檔案。The following snippets are from the src/main/java/com/azure/cosmosdb/cassandra/repository/UserRepository.java file.

  • 建立新的 keyspace。Create a new keyspace.

    public void createKeyspace() {
        final String query = "CREATE KEYSPACE IF NOT EXISTS uprofile WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3' } ";
        session.execute(query);
        LOGGER.info("Created keyspace 'uprofile'");
    }
    
  • 建立新的資料表。Create a new table.

    public void createTable() {
          final String query = "CREATE TABLE IF NOT EXISTS uprofile.user (user_id int PRIMARY KEY, user_name text, user_bcity text)";
          session.execute(query);
          LOGGER.info("Created table 'user'");
    }
    
  • 使用備妥的陳述式物件插入使用者實體。Insert user entities using a prepared statement object.

    public PreparedStatement prepareInsertStatement() {
        final String insertStatement = "INSERT INTO  uprofile.user (user_id, user_name , user_bcity) VALUES (?,?,?)";
        return session.prepare(insertStatement);
    }
    
    public void insertUser(PreparedStatement statement, int id, String name, String city) {
        BoundStatement boundStatement = new BoundStatement(statement);
        session.execute(boundStatement.bind(id, name, city));
    }
    
  • 取得所有使用者資訊的查詢。Query to get all user information.

    public void selectAllUsers() {
        final String query = "SELECT * FROM uprofile.user";
        List<Row> rows = session.execute(query).all();
    
        for (Row row : rows) {
            LOGGER.info("Obtained row: {} | {} | {} ", row.getInt("user_id"), row.getString("user_name"), row.getString("user_bcity"));
        }
    }
    
  • 取得單一使用者資訊的查詢。Query to get a single user's information.

    public void selectUser(int id) {
        final String query = "SELECT * FROM uprofile.user where user_id = 3";
        Row row = session.execute(query).one();
    
        LOGGER.info("Obtained row: {} | {} | {} ", row.getInt("user_id"), row.getString("user_name"), row.getString("user_bcity"));
    }
    

更新您的連接字串Update your connection string

現在,返回 Azure 入口網站以取得連接字串資訊,並將它複製到應用程式中。Now go back to the Azure portal to get your connection string information and copy it into the app. 連接字串詳細資料可讓您的應用程式與託管資料庫進行通訊。The connection string details enable your app to communicate with your hosted database.

  1. Azure 入口網站中,選取 [連接字串] 。In the Azure portal, select Connection String.

    從 Azure 入口網站 [連接字串] 頁面檢視及複製使用者名稱

  2. 使用Use the 畫面右方的 [複製] 按鈕 來複製 [連絡點] 值。button on the right side of the screen to copy the CONTACT POINT value.

  3. 開啟 C:\git-samples\azure-cosmosdb-cassandra-java-getting-started\java-examples\src\main\resources 資料夾中的 config.properties 檔案。Open the config.properties file from C:\git-samples\azure-cosmosdb-cassandra-java-getting-started\java-examples\src\main\resources folder.

  4. 從入口網站將 [連絡點] 值貼到 <Cassandra endpoint host> 的行 2。Paste the CONTACT POINT value from the portal over <Cassandra endpoint host> on line 2.

    config.properties 的第 2 行現在看起來應該類似於Line 2 of config.properties should now look similar to

    cassandra_host=cosmos-db-quickstart.cassandra.cosmosdb.azure.com

  5. 返回入口網站,並複製 [使用者名稱] 值。Go back to portal and copy the USERNAME value. 從入口網站將 [使用者名稱] 值貼到 <cassandra endpoint username> 的行 4。Past the USERNAME value from the portal over <cassandra endpoint username> on line 4.

    config.properties 的第 4 行現在看起來應該類似於Line 4 of config.properties should now look similar to

    cassandra_username=cosmos-db-quickstart

  6. 返回入口網站,並複製 [密碼] 值。Go back to portal and copy the PASSWORD value. 從入口網站將 [密碼] 值貼到 <cassandra endpoint password> 的行 5。Paste the PASSWORD value from the portal over <cassandra endpoint password> on line 5.

    config.properties 的第 5 行現在看起來應該類似於Line 5 of config.properties should now look similar to

    cassandra_password=2Ggkr662ifxz2Mg...==

  7. 在第 6 行中,如果您想要使用特定的 SSL 憑證,請將 <SSL key store file location> 取代為 SSL 憑證的位置。On line 6, if you want to use a specific SSL certificate, then replace <SSL key store file location> with the location of the SSL certificate. 如果未提供值,會使用安裝在 <JAVA_HOME>/jre/lib/security/cacerts 的 JDK 憑證。If a value is not provided, the JDK certificate installed at <JAVA_HOME>/jre/lib/security/cacerts is used.

  8. 如果您變更行 6 為使用特定的 SSL 憑證,請更新行 7 以使用該憑證的密碼。If you changed line 6 to use a specific SSL certificate, update line 7 to use the password for that certificate.

  9. 儲存 config.properties 檔案。Save the config.properties file.

執行 Java 應用程式Run the Java app

  1. 在 git 終端機視窗中,cdazure-cosmosdb-cassandra-java-getting-started\java-examples 資料夾。In the git terminal window, cd to the azure-cosmosdb-cassandra-java-getting-started\java-examples folder.

    cd "C:\git-samples\azure-cosmosdb-cassandra-java-getting-started\java-examples"
    
  2. 在 git 終端機視窗中,使用下列命令產生 cosmosdb-cassandra-examples.jar 檔案。In the git terminal window, use the following command to generate the cosmosdb-cassandra-examples.jar file.

    mvn clean install
    
  3. 在 git 終端機視窗中,執行下列命令以啟動 JAVA 應用程式。In the git terminal window, run the following command to start the Java application.

    java -cp target/cosmosdb-cassandra-examples.jar com.azure.cosmosdb.cassandra.examples.UserProfile
    

    終端機視窗會顯示 keyspace 和資料表已建立的通知。The terminal window displays notifications that the keyspace and table are created. 它會接著選取並傳回資料表中的所有使用者並顯示輸出,然後依識別碼選取資料列並顯示值。It then selects and returns all users in the table and displays the output, and then selects a row by ID and displays the value.

    選取 CTRL + C 來停止執行程式,並關閉主控台視窗。Select CTRL + C to stop execution of the program and close the console window.

  4. 在 Azure 入口網站中,開啟 [資料總管] 以查詢、修改及使用這個新資料。In the Azure portal, open Data Explorer to query, modify, and work with this new data.

    在資料總管中檢視資料

在 Azure 入口網站中檢閱 SLAReview SLAs in the Azure portal

Azure 入口網站會監視您的 Cosmos DB 帳戶輸送量、儲存體、可用性、延遲和一致性。The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Azure Cosmos DB 服務等級協定 (SLA) 相關聯的計量圖表會顯示相較於實際效能的 SLA 值。Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. 此計量套件可讓您以更透明的方式監視監視 SLA。This suite of metrics makes monitoring your SLAs transparent.

若要檢閱計量和 SLA:To review metrics and SLAs:

  1. 在您的 Cosmos DB 帳戶導覽功能表中,選取 [計量] 。Select Metrics in your Cosmos DB account's navigation menu.

  2. 選取一個索引標籤 (例如 [延遲] ),並在右側選取時間範圍。Select a tab such as Latency, and select a timeframe on the right. 比較圖表中的實際SLA 的資料行。Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB 計量套件

  3. 檢閱其他索引標籤中的計量。Review the metrics on the other tabs.

清除資源Clean up resources

完成您的 Web 應用程式和 Azure Cosmos DB 帳戶之後,您可以將建立的 Azure 資源刪除,以免產生更多費用。When you're done with your web app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. 若要刪除資源:To delete the resources:

  1. 在 Azure 入口網站中,選取最左邊的 [資源群組] 。In the Azure portal, select Resource groups on the far left. 若已摺疊左側功能表,請選取展開按鈕加以展開。If the left menu is collapsed, select Expand button to expand it.

  2. 選取您在本快速入門中建立的資源群組。Select the resource group you created for this quickstart.

    Azure 入口網站中的計量

  3. 在新視窗中,選取 [刪除資源群組] 。In the new window, select Delete resource group.

    Azure 入口網站中的計量

  4. 在下個視窗中輸入要刪除的資源群組名稱,然後選取 [刪除] 。In the next window, enter the name of the resource group to delete, and then select Delete.

後續步驟Next steps

在本快速入門中,您已了解如何使用 [資料總管] 來建立 Azure Cosmos DB 帳戶、Cassandra 資料庫和容器,以及如何執行應用程式來以程式設計方式執行同樣的作業。In this quickstart, you've learned how to create an Azure Cosmos DB account, Cassandra database, and container using the Data Explorer, and run an app to do the same thing programmatically. 您現可將其他資料匯入至 Azure Cosmos 容器。You can now import additional data into your Azure Cosmos container.