快速入门:生成 Java 应用以管理 Azure Cosmos DB Cassandra API 数据(v4 驱动程序)Quickstart: Build a Java app to manage Azure Cosmos DB Cassandra API data (v4 Driver)

在本快速入门中,你将创建一个 Azure Cosmos DB Cassandra API 帐户,并使用从 GitHub 克隆的 Cassandra Java 应用通过 Java 的 v4.x Apache Cassandra 驱动程序创建一个 Cassandra 数据库和一个容器。In this quickstart, you create an Azure Cosmos DB Cassandra API account, and use a Cassandra Java app cloned from GitHub to create a Cassandra database and container using the v4.x Apache Cassandra drivers for Java. Azure Cosmos DB 是一种多模型数据库服务,可让你通过多区域分布和水平缩放功能快速创建和查询文档、表、键/值和图数据库。Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with multiple-region distribution and horizontal scale capabilities.

先决条件Prerequisites

创建数据库帐户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. 在左侧菜单中,选择“创建资源” 。In the left menu, select Create a resource.

    在 Azure 门户中创建资源

  3. 在“新建”页上,选择“数据库” > “Azure Cosmos DB”。 On the New page, select Databases > Azure Cosmos DB.

    Azure 门户“数据库”窗格

  4. 在“创建 Azure Cosmos DB 帐户”页中,输入新 Azure Cosmos DB 帐户的设置 。On 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 name as Account Name
    选择“新建”。 Select Create new. 然后输入帐户的新资源组名称。Then enter a new resource group name for your account. 为简单起见,请使用与 Azure Cosmos 帐户名称相同的名称。For simplicity, use the same name as your Azure Cosmos account name.
    帐户名Account Name 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account. 帐户 URI 将是追加到唯一帐户名称的“cassandra.cosmos.azure.cn” 。Your account URI will be cassandra.cosmos.azure.cn appended to your unique account name.

    帐户名称只能使用小写字母、数字及连字符 (-),必须为 3 到 31 个字符长。The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    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 创建单独的帐户。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 的“新建帐户”页

  5. 创建帐户需要几分钟时间。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 bash 之类的 git 终端窗口,并使用 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-v4.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.

  • CqlSession 连接到 Azure Cosmos DB Cassandra API 并返回可供访问的会话(v3 驱动程序中的 Cluster 对象现已过时)。The CqlSession connects to the Azure Cosmos DB Cassandra API and returns a session to access (Cluster object from v3 driver is now obsolete). Cassandra 主机、端口、用户名和密码是使用 Azure 门户中的连接字符串页设置的。Cassandra Host, Port, User name and password is set using the connection string page in the Azure portal.

    this.session = CqlSession.builder().withSslContext(sc)
            .addContactPoint(new InetSocketAddress(cassandraHost, cassandraPort)).withLocalDatacenter(region)
            .withAuthCredentials(cassandraUsername, cassandraPassword).build();
    

以下代码片段来自 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.

  • 如果密钥空间自上次运行的时候已存在,则删除该密钥空间。Drop the keyspace if it already exists from a previous run.

    public void dropKeyspace() {
        String query = "DROP KEYSPACE IF EXISTS "+keyspace+"";
        session.execute(query);
        LOGGER.info("dropped keyspace '"+keyspace+"'");
    } 
    
  • 创建新的键空间。A new keyspace is created.

    public void createKeyspace() {
        String query = "CREATE KEYSPACE "+keyspace+" WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 }";
        session.execute(query);
        LOGGER.info("Created keyspace '"+keyspace+"'");
    }
    
  • 创建新表。A new table is created.

    public void createTable() {
        String query = "CREATE TABLE "+keyspace+"."+table+" (user_id int PRIMARY KEY, user_name text, user_bcity text)";
        session.execute(query);
        LOGGER.info("Created table '"+table+"'");
    }
    
  • 使用预定义的语句对象插入用户实体。User entities are inserted using a prepared statement object.

    public String prepareInsertStatement() {
        final String insertStatement = "INSERT INTO  "+keyspace+"."+table+" (user_id, user_name , user_bcity) VALUES (?,?,?)";
        return insertStatement;
    }
    
    public void insertUser(String preparedStatement, int id, String name, String city) {
        PreparedStatement prepared = session.prepare(preparedStatement);
        BoundStatement bound = prepared.bind(id, city, name).setIdempotent(true);
        session.execute(bound);
    }
    
  • 通过查询获取所有用户信息。Query to get get all User information.

    public void selectAllUsers() {
        final String query = "SELECT * FROM "+keyspace+"."+table+"";
        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 information.

    public void selectUser(int id) {
        final String query = "SELECT * FROM "+keyspace+"."+table+" 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 门户的 Azure Cosmos DB 帐户中,选择“连接字符串”。In your Azure Cosmos DB account in the Azure portal, select Connection String.

    在 Azure 门户的“连接字符串”页面中查看并复制用户名

  2. 使用屏幕右侧的 按钮复制“CONTACT POINT”值。

  3. 打开 C:\git-samples\azure-cosmosdb-cassandra-java-getting-started\java-examples\src\main\resources 文件夹中的 config.properties 文件。Open the config.properties file from the C:\git-samples\azure-cosmosdb-cassandra-java-getting-started\java-examples\src\main\resources folder.

  4. 粘贴门户中的“联系点”值,并覆盖第 2 行中的 <Cassandra endpoint host>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.cosmos.azure.cn

  5. 返回到门户,并复制“用户名”值。Go back to the portal and copy the USERNAME value. 粘贴门户中的“用户名”值,并覆盖第 4 行中的 <cassandra endpoint username>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 the portal and copy the PASSWORD value. 粘贴门户中的“密码”值,并覆盖第 5 行中的 <cassandra endpoint password>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 行中,如果需要使用特定的 TLS/SSL 证书,请将 <SSL key store file location> 替换为该 TLS/SSL 证书的位置。On line 6, if you want to use a specific TLS/SSL certificate, then replace <SSL key store file location> with the location of the TLS/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 行更改为使用特定的 TLS/SSL 证书,请将第 7 行更新为对该证书使用密码。If you changed line 6 to use a specific TLS/SSL certificate, update line 7 to use the password for that certificate.

  9. 请注意,需要为联系点添加默认区域(例如China North),例如Note that you will need to add the default region (e.g. China North) for the contact point, e.g.

    region=China North

    这是因为 v.4x 驱动程序只允许将一个本地 DC 与联系点配对。This is because the v.4x driver only allows one local DC to be paired with the contact point. 如果要添加默认区域以外的区域(这是首次创建 Cosmos DB 帐户时给出的区域),则需要在添加联系点时使用区域后缀,例如 host-chinanorth.cassandra.cosmos.azure.cnIf you want to add a region other than the default (which is the region that was given when the Cosmos DB account was first created), you will need to use regional suffix when adding contact point, e.g. host-chinanorth.cassandra.cosmos.azure.cn.

  10. 保存 config.properties 文件。Save the config.properties file.

运行 Java 应用Run the Java app

  1. 在 git 终端窗口中,通过 cd 转至 azure-cosmosdb-cassandra-java-getting-started-v4 文件夹。In the git terminal window, cd to the azure-cosmosdb-cassandra-java-getting-started-v4 folder.

    cd "C:\git-samples\azure-cosmosdb-cassandra-java-getting-started-v4"
    
  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
    

    终端窗口会显示通知,指出密钥空间和表已创建。The terminal window displays notifications that the keyspace and table are created. 然后,它会选择并返回表中的所有用户,然后显示输出,接着按 ID 选择行并显示值。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 停止执行程序并关闭控制台窗口。Press 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 Cosmos DB

在 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

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。When you're done with your 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 Search bar, search for and select Resource groups.

  2. 从列表中选择为本快速入门创建的资源组。From the list, select the resource group you created for this quickstart.

    选择要删除的资源组

  3. 在资源组“概览”页上,选择“删除资源组” 。On the resource group Overview page, select Delete resource group.

    删除资源组

  4. 在下一窗口中输入要删除的资源组的名称,然后选择“删除” 。In the next window, enter the name of the resource group to delete, and then select Delete.

后续步骤Next steps

本快速入门介绍了如何使用 Cassandra API 创建 Azure Cosmos DB 帐户,以及如何运行用于创建 Cassandra 数据库和容器的 Cassandra Java 应用。In this quickstart, you learned how to create an Azure Cosmos DB account with Cassandra API, and run a Cassandra Java app that creates a Cassandra database and container. 现在可以将其他数据导入 Azure Cosmos DB 帐户了。You can now import additional data into your Azure Cosmos DB account.