共用方式為


快速入門:適用於 Java 的 Azure Cosmos DB for Apache Cassandra 用戶端程式庫

開始使用適用於 Java 的 Azure Cosmos DB for Apache Cassandra 用戶端程式庫,以儲存、管理和查詢非結構化資料。 請依照本指南中的步驟建立新帳戶、安裝 Java 用戶端程式庫、連線到帳戶、執行一般作業,以及查詢最終範例資料。

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

先決條件

  • Azure 訂用帳戶

    • 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶
  • Java 21 或更新版本

設定

首先,設定本指南的帳號和開發環境。 本節將引導您進行創建帳戶、獲取其憑證,然後準備開發環境。

建立帳戶

首先,建立適用於 Apache Cassandra 帳戶的 API。 建立帳戶之後,請建立金鑰空間和資料表資源。

  1. 如果您還沒有目標資源群組,請使用命令 az group create 在訂用帳戶中建立新的資源群組。

    az group create \
        --name "<resource-group-name>" \
        --location "<location>"
    
  2. 使用 az cosmosdb create 命令,新建具有預設設定的 Azure Cosmos DB Apache Cassandra 帳戶。

    az cosmosdb create \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --locations "regionName=<location>" \
        --capabilities "EnableCassandra"
    
  3. 使用 az cosmosdb cassandra keyspace create 名為 cosmicworks建立新的keyspace。

    az cosmosdb cassandra keyspace create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --name "cosmicworks"
    
  4. 建立新的 JSON 物件,以使用多行 Bash 命令來代表您的結構描述。 然後,使用 az cosmosdb cassandra table create 命令來建立名為 products的新數據表。

    schemaJson=$(cat <<EOF
    {
      "columns": [
        {
          "name": "id",
          "type": "text"
        },
        {
          "name": "name",
          "type": "text"
        },
        {
          "name": "category",
          "type": "text"
        },
        {
          "name": "quantity",
          "type": "int"
        },
        {
          "name": "price",
          "type": "decimal"
        },
        {
          "name": "clearance",
          "type": "boolean"
        }
      ],
      "partitionKeys": [
        {
          "name": "id"
        }
      ]
    }
    EOF
    )
    
    az cosmosdb cassandra table create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --keyspace-name "cosmicworks" \
        --name "product" \
        --schema "$schemaJson"
    

取得認證

現在,取得客戶端程式庫所需的密碼,以建立與最近創建的帳戶的連接。

  1. 使用 az cosmosdb show 來取得帳戶的聯絡點和使用者名稱。

    az cosmosdb show \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --query "{username:name,contactPoint:documentEndpoint}"
    
  2. 記錄先前命令輸出中contactPointusername屬性的值。 這些屬性的值是您在本指南稍後用來連線至資料庫帳戶的 聯絡點使用者名稱

  3. 使用 az cosmosdb keys list 可獲得帳戶的 金鑰

    az cosmosdb keys list \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --type "keys"
    
  4. 記錄先前命令輸出中屬性 primaryMasterKey 的值。 此屬性的值是您在本指南稍後用來連線至程式庫帳戶的 密碼

準備開發環境

然後,使用新專案和用戶端程式庫來設定您的開發環境。 此步驟是繼續本指南其餘部分之前的最後一個必要先決條件。

  1. 從空白目錄開始。

  2. 使用 Maven 產生新的 Java 主控台專案。

    mvn archetype:generate -DgroupId=quickstart -DartifactId=console -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    
  3. 從Maven匯入 java-driver-core 套件。 將此區段新增至您的 pom.xml 檔案。

    <dependency>
      <groupId>org.apache.cassandra</groupId>
      <artifactId>java-driver-core</artifactId>
      <version>[4.,)</version>
    </dependency>
    
  4. 開啟 /console/src/main/java/quickstart/App.java 檔案。

  5. 觀察現有的 Java 應用程式樣板。

    package quickstart;
    
    /**
     * Hello world!
     *
     */
    public class App 
    {
        public static void main( String[] args )
        {
            System.out.println( "Hello World!" );
        }
    }
    
  6. 從重複使用中移除註解和主控台輸出。 此程式碼區塊是本指南其餘部分的起點。

    package quickstart;
    
    public class App 
    {
        public static void main(String[] args)
        {
        }
    }
    
  7. 匯入 java.security.NoSuchAlgorithmException 命名空間。

    import java.security.NoSuchAlgorithmException;
    
  8. 更新 main 方法簽章,指出它可以擲回 NoSuchAlgorithmException 例外狀況。

    public static void main(String[] args) throws NoSuchAlgorithmException
    {    
    }
    

    這很重要

    本指南中的其餘步驟假設您要在方法中 main 新增程式碼。

  9. 建置專案。

    mvn compile
    

物件模型

說明
CqlSession 表示叢集的特定連線
PreparedStatement 表示預先編譯的 CQL 陳述式,可以有效率地執行多次
BoundStatement 表示具有繫結參數的預備陳述式
Row 代表查詢結果的單一資料列

程式碼範例

驗證用戶端

首先,使用本指南稍早收集的認證來驗證用戶端。

  1. 在整合開發環境 (IDE) 中開啟 /console/src/main/java/quickstart/App.java 檔案。

  2. 匯入下列類型:

    • java.net.InetSocketAddress
    • javax.net.ssl.SSLContext
    • com.datastax.oss.driver.api.core.CqlIdentifier
    • com.datastax.oss.driver.api.core.CqlSession
    • com.datastax.oss.driver.api.core.cql.BoundStatement
    • com.datastax.oss.driver.api.core.cql.PreparedStatement
    • com.datastax.oss.driver.api.core.cql.ResultSet
    • com.datastax.oss.driver.api.core.cql.Row
    import java.net.InetSocketAddress;    
    
    import javax.net.ssl.SSLContext;
    
    import com.datastax.oss.driver.api.core.CqlIdentifier;
    import com.datastax.oss.driver.api.core.CqlSession;
    import com.datastax.oss.driver.api.core.cql.BoundStatement;
    import com.datastax.oss.driver.api.core.cql.PreparedStatement;
    import com.datastax.oss.driver.api.core.cql.ResultSet;
    import com.datastax.oss.driver.api.core.cql.Row;
    
  3. 為本指南稍早收集的認證建立字串變數。 將變數 username命名為 、 passwordcontactPoint。 此外,請建立以本機資料中心命名 region 的字串變數。

    String username = "<username>";
    String password = "<password>";
    String contactPoint = "<contact-point>";
    
  4. 針對您建立 Azure Cosmos DB for Apache Cassandra 帳戶所在的區域建立另一個字串變數。 將此變數 region命名為 。

    String region = "<region>";
    
  5. 建立物件 SSLContext 以確保您使用的是傳輸層安全性 (TLS) 通訊協定。

    SSLContext sslContext = SSLContext.getDefault();
    
  6. 使用先前步驟中建立的認證和組態變數來建立新 CqlSession 物件。 設定聯絡點、本機資料中心、驗證認證、金鑰空間和傳輸層安全性 (TLS) 環境定義。

    CqlSession session = CqlSession.builder()
        .addContactPoint(new InetSocketAddress(contactPoint, 10350))
        .withLocalDatacenter(region)
        .withAuthCredentials(username, password)
        .withKeyspace(CqlIdentifier.fromCql("cosmicworks"))
        .withSslContext(sslContext)
        .build();
    

警告

本指南已停用完整的傳輸層安全性 (TLS) 驗證,以簡化驗證。 針對生產環境部署,請完全啟用驗證。

更新插入資料

接下來,將新資料「更新或插入」到資料表中。 更新插入可確保根據資料表中是否已存在相同的資料,適當地建立或取代資料。

  1. 定義一個名為的新 Product 類別,其欄位對應於本指南稍早建立的資料表。

    class Product {
        public String id;
        public String name;
        public String category;
        public int quantity;
        public boolean clearance;
    
        public Product(String id, String name, String category, int quantity, boolean clearance) {
            this.id = id;
            this.name = name;
            this.category = category;
            this.quantity = quantity;
            this.clearance = clearance;
        }
    
        @Override
        public String toString() {
            return String.format("Product{id='%s', name='%s', category='%s', quantity=%d, clearance=%b}",
                    id, name, category, quantity, clearance);
        }
    }
    

    小提示

    在 Java 中,您可以在另一個檔案中建立此類型,或在現有檔案的結尾建立它。

  2. 建立類型的 Product新物件。 將物件儲存在名為 product的變數中。

    Product product = new Product(
        "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
        "Yamba Surfboard",
        "gear-surf-surfboards",
        12,
        false
    );
    
  3. 建立以 Cassandra 查詢語言 (CQL) 查詢命名 insertQuery 的新字串變數,以插入新資料列。

    String insertQuery = "INSERT INTO product (id, name, category, quantity, clearance) VALUES (?, ?, ?, ?, ?)";
    
  4. 準備insert語句,並將產品屬性繫結為參數。

    PreparedStatement insertStmt = session.prepare(insertQuery);
    BoundStatement boundInsert = insertStmt.bind(
        product.id,
        product.name,
        product.category,
        product.quantity,
        product.clearance
    );
    
  5. 執行繫結陳述式以 upsert 產品。

    session.execute(boundInsert);
    

讀取資料

然後,讀取先前更新插入資料表的資料。

  1. 建立一個名為 CQL 查詢的新 readQuery 字串變數,以匹配具有相同 id 欄位的項目。

    String readQuery = "SELECT * FROM product WHERE id = ? LIMIT 1";
    
  2. 建立一個字串變數,其值 id 與本指南稍早建立的產品具有相同的值。

    String id = "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb";
    
  3. 準備語句,並將產品的 id 欄位綁定為參數。

    PreparedStatement readStmt = session.prepare(readQuery);
    BoundStatement boundRead = readStmt.bind(id);
    
  4. 執行綁定語句,並將結果儲存在名為 readResult的變數中。

    ResultSet readResult = session.execute(boundRead);
    
  5. 從結果集中擷取第一列,並將其對應至物件 Product (如果找到)。

    Row row = readResult.one();
    Product matchedProduct = new Product(
        row.getString("id"),
        row.getString("name"),
        row.getString("category"),
        row.getInt("quantity"),
        row.getBoolean("clearance")
    );
    

查詢數據

現在,使用查詢來尋找與資料表中特定篩選器相符的所有資料。

  1. 建立一個名為 CQL 查詢的新 findQuery 字串變數,以匹配具有相同 category 欄位的項目。

    String findQuery = "SELECT * FROM product WHERE category = ? ALLOW FILTERING";
    
  2. 建立一個字串變數,其值 id 與本指南稍早建立的產品具有相同的值。

    String category = "gear-surf-surfboards";
    
  3. 準備報表,並將產品類別綁定為參數。

    PreparedStatement findStmt = session.prepare(findQuery);
    BoundStatement boundFind = findStmt.bind(category);
    
  4. 執行綁定語句,並將結果儲存在名為 findResults的變數中。

    ResultSet results = session.execute(boundFind);
    
  5. 逐一查看查詢結果,並將每一列對應至物件 Product

    for (Row result : results) {
        Product queriedProduct = new Product(
            result.getString("id"),
            result.getString("name"),
            result.getString("category"),
            result.getInt("quantity"),
            result.getBoolean("clearance")
        );
        // Do something here with each result
    }
    

關閉工作階段

在 Java 中,您需要在完成任何查詢和操作後關閉會話。

session.close();

執行程式碼

使用應用程式目錄中的終端機執行新建立的應用程式。

mvn compile
mvn exec:java -Dexec.mainClass="quickstart.App"

小提示

請確定您在本指南中建立的 /console 路徑內執行此命令。

清理資源

現在,取得客戶端程式庫所需的密碼,以建立與最近創建的帳戶的連接。

  1. 使用 az cosmosdb show 來取得帳戶的聯絡點和使用者名稱。

    az cosmosdb show \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --query "{username:name,contactPoint:documentEndpoint}"
    
  2. 記錄先前命令輸出中contactPointusername屬性的值。 這些屬性的值是您在本指南稍後用來連線至資料庫帳戶的 聯絡點使用者名稱

  3. 使用 az cosmosdb keys list 可獲得帳戶的 金鑰

    az cosmosdb keys list \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --type "keys"
    
  4. 記錄先前命令輸出中屬性 primaryMasterKey 的值。 此屬性的值是您在本指南稍後用來連線至程式庫帳戶的 密碼

後續步驟