教程:使用 Java 应用程序在 Azure Cosmos DB 中创建 Cassandra API 帐户,以便存储键/值数据Tutorial: Create a Cassandra API account in Azure Cosmos DB by using a Java application to store key/value data

作为开发人员,你可能具有使用键/值对的应用程序。As a developer, you might have applications that use key/value pairs. 可以在 Azure Cosmos DB 中使用 Cassandra API 帐户来存储键/值数据。You can use a Cassandra API account in Azure Cosmos DB to store the key/value data. 本教程介绍如何使用 Java 应用程序在 Azure Cosmos DB 中创建 Cassandra API 帐户、添加数据库(也称为键空间)以及添加表。This tutorial describes how to use a Java application to create a Cassandra API account in Azure Cosmos DB, add a database (also called a keyspace), and add a table. Java 应用程序使用 Java 驱动程序来创建包含用户 ID、用户名、用户城市等详细信息的用户数据库。The Java application uses the Java driver to create a user database that contains details such as user ID, user name, and user city.

本教程涵盖以下任务:This tutorial covers the following tasks:

  • 创建 Cassandra 数据库帐户Create a Cassandra database account
  • 获取帐户连接字符串Get the account connection string
  • 创建 Maven 项目和依赖项Create a Maven project and dependencies
  • 添加数据库和表Add a database and a table
  • 运行应用程序Run the app

先决条件Prerequisites

创建数据库帐户Create a database account

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 选择“创建资源”**** > ****“数据库” > ****“Azure Cosmos DB”。Select Create a resource > Databases > Azure Cosmos DB.

  3. 在“新建帐户”窗格上,输入新 Azure Cosmos 帐户的设置。****In the New account pane, enter the settings for the new Azure Cosmos account.

    设置Setting 建议的值Suggested value 说明Description
    IDID 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos 帐户的唯一名称。Enter a unique name to identify this Azure Cosmos account.

    由于 cassandra.cosmos.azure.cn 将追加到所提供的用于创建接触点的 ID 后面,因此,请使用唯一但可识别的 ID。Because cassandra.cosmos.azure.cn is appended to the ID that you provide to create your contact point, use a unique but identifiable ID.
    APIAPI CassandraCassandra API 确定要创建的帐户的类型。The API determines the type of account to create.
    选择“Cassandra”,因为在本文中,你将创建可使用 Cassandra 查询语言 (CQL) 语法查询的宽列数据库****。Select Cassandra, because in this article you will create a wide-column database that can be queried by using Cassandra Query Language (CQL) syntax.
    订阅Subscription 你的订阅Your subscription 选择要用于此 Azure Cosmos 帐户的 Azure 订阅。Select Azure subscription that you want to use for this Azure Cosmos account.
    资源组Resource Group 输入名称Enter a name 选择“新建”,然后输入帐户的新资源组名称****。Select Create New, and then enter a new resource-group name for your account. 为简单起见,可以使用与 ID 相同的名称。For simplicity, you can use the same name as your ID.
    位置Location 选择离用户最近的区域Select the region closest to your users 选择要在其中托管 Azure Cosmos 帐户的地理位置。Select the geographic location in which to host your Azure Cosmos account. 使用离用户最近的位置,使他们能够以最快的速度访问数据。Use the location that's closest to your users, to give them the fastest access to the data.

    使用门户创建帐户

  4. 选择“创建” ****。Select Create.
    创建帐户需要几分钟时间。The account creation takes a few minutes. 创建资源后,可以在门户右侧看到“部署成功”**** 通知。After the resource is created, you can see the Deployment succeeded notification on the right side of the portal.

获取帐户的连接详细信息Get the connection details of your account

从 Azure 门户获取连接字符串信息,并将其复制到 Java 配置文件。Get the connection string information from the Azure portal, and copy it into the Java configuration file. 连接字符串使应用能与托管数据库进行通信。The connection string enables your app to communicate with your hosted database.

  1. Azure 门户转到 Azure Cosmos 帐户。From the Azure portal, go to your Azure Cosmos account.

  2. 打开“连接字符串”**** 窗格。Open the Connection String pane.

  3. 复制接触点、端口、用户名以及主密码值,以便在后续步骤中使用**** **** **** ****。Copy the CONTACT POINT, PORT, USERNAME, and PRIMARY PASSWORD values to use in the next steps.

创建项目和依赖项Create the project and the dependencies

本文中使用的 Java 示例项目托管在 GitHub 中。The Java sample project that you use in this article is hosted in GitHub. 可以运行本文档中的步骤,也可以从 azure-cosmos-db-cassandra-java-getting-started 存储库下载示例。You can run the steps in this doc or download the sample from the azure-cosmos-db-cassandra-java-getting-started repository.

下载文件后,更新 java-examples\src\main\resources\config.properties 文件中的连接字符串信息并运行它。After you download the files, update the connection string information within the java-examples\src\main\resources\config.properties file and run it.

cassandra_host=<FILLME_with_CONTACT POINT> 
cassandra_port = 10350 
cassandra_username=<FILLME_with_USERNAME> 
cassandra_password=<FILLME_with_PRIMARY PASSWORD> 

若要从头生成示例,请执行以下步骤:Use the following steps to build the sample from scratch:

  1. 在终端窗口或命令提示符中,创建名为 Cassandra-demo 的新 Maven 项目。From the terminal or command prompt, create a new Maven project called Cassandra-demo.

    mvn archetype:generate -DgroupId=com.azure.cosmosdb.cassandra -DartifactId=cassandra-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 
    
  2. 找到 cassandra-demo 文件夹。Locate the cassandra-demo folder. 使用文本编辑器打开已生成的 pom.xml 文件。Using a text editor, open the pom.xml file that was generated.

    添加 Cassandra 依赖项并生成项目所需的插件,如 pom.xml 文件中所示。Add the Cassandra dependencies and build plugins required by your project, as shown in the pom.xml file.

  3. cassandra-demo\src\main 文件夹下,创建名为 resources 的新文件夹。Under the cassandra-demo\src\main folder, create a new folder named resources. 在资源文件夹下,添加 config.properties 和 log4j.properties 文件:Under the resources folder, add the config.properties and log4j.properties files:

    • Config.properties 文件存储 Cassandra API 帐户的连接终结点和键值。The config.properties file stores the connection endpoint and key values of the Cassandra API account.

    • log4j.properties 文件定义与 Cassandra API 交互所需的日志记录级别。The log4j.properties file defines the level of logging required for interacting with the Cassandra API.

  4. 浏览到 src/main/java/com/azure/cosmosdb/cassandra/ 文件夹。Browse to the src/main/java/com/azure/cosmosdb/cassandra/ folder. 在 cassandra 文件夹中,另创建一个名为 utils 的文件夹。Within the cassandra folder, create another folder named utils. 新的文件夹存储连接到 Cassandra API 帐户所需的实用程序类。The new folder stores the utility classes required to connect to the Cassandra API account.

    添加 CassandraUtils 类来创建群集并打开和关闭 Cassandra 会话。Add the CassandraUtils class to create the cluster and to open and close Cassandra sessions. 群集将连接到 Azure Cosmos DB 中的 Cassandra API 帐户并返回可供访问的会话。The cluster connects to the Cassandra API account in Azure Cosmos DB and returns a session to access. 使用 Configurations 类从 config.properties 文件中读取连接字符串信息。Use the Configurations class to read connection string information from the config.properties file.

  5. Java 示例使用用户信息(如用户名、用户ID、用户城市)创建数据库。The Java sample creates a database with user information such as user name, user ID, and user city. 你需要定义 get 和 set 方法以访问主函数中的用户详细信息。You need to define get and set methods to access user details in the main function.

    使用 get 和 set 方法在 src/main/java/com/azure/cosmosdb/cassandra/ 文件夹下创建 User.java 类。Create a User.java class under the src/main/java/com/azure/cosmosdb/cassandra/ folder with get and set methods.

添加数据库和表Add a database and a table

本部分介绍如何添加数据库(键空间)和表,方法是使用 CQL。This section describes how to add a database (keyspace) and a table, by using CQL.

  1. src\main\java\com\azure\cosmosdb\cassandra 文件夹下,创建名为 repository 的新文件夹。Under the src\main\java\com\azure\cosmosdb\cassandra folder, create a new folder named repository.

  2. 创建 UserRepository Java 类,并向其添加以下代码:Create the UserRepository Java class and add the following code to it:

    package com.azure.cosmosdb.cassandra.repository; 
    import java.util.List; 
    import com.datastax.driver.core.BoundStatement; 
    import com.datastax.driver.core.PreparedStatement; 
    import com.datastax.driver.core.Row; 
    import com.datastax.driver.core.Session; 
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 
    
    /** 
    * Create a Cassandra session 
    */ 
    public class UserRepository { 
    
       private static final Logger LOGGER = LoggerFactory.getLogger(UserRepository.class); 
       private Session session; 
       public UserRepository(Session session) { 
           this.session = session; 
       } 
    
       /** 
       * Create keyspace uprofile in cassandra DB 
        */ 
    
       public void createKeyspace() { 
            final String query = "CREATE KEYSPACE IF NOT EXISTS uprofile WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 }"; 
           session.execute(query); 
           LOGGER.info("Created keyspace 'uprofile'"); 
       } 
    
       /** 
        * Create user table in cassandra DB 
        */ 
    
       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'"); 
       } 
    } 
    
  3. 找到 src\main\java\com\azure\cosmosdb\cassandra 文件夹,并创建名为 examples 的新的子文件夹。Locate the src\main\java\com\azure\cosmosdb\cassandra folder, and create a new subfolder named examples.

  4. 创建 UserProfile Java 类。Create the UserProfile Java class. 此类包含调用前面定义的 createKeyspace 和 createTable 方法的主方法:This class contains the main method that calls the createKeyspace and createTable methods you defined earlier:

    package com.azure.cosmosdb.cassandra.examples; 
    import java.io.IOException; 
    import com.azure.cosmosdb.cassandra.repository.UserRepository; 
    import com.azure.cosmosdb.cassandra.util.CassandraUtils; 
    import com.datastax.driver.core.PreparedStatement; 
    import com.datastax.driver.core.Session; 
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 
    
    /** 
    * Example class which will demonstrate following operations on Cassandra Database on CosmosDB 
    * - Create Keyspace 
    * - Create Table 
    * - Insert Rows 
    * - Select all data from a table 
    * - Select a row from a table 
    */ 
    
    public class UserProfile { 
    
       private static final Logger LOGGER = LoggerFactory.getLogger(UserProfile.class); 
       public static void main(String[] s) throws Exception { 
           CassandraUtils utils = new CassandraUtils(); 
           Session cassandraSession = utils.getSession(); 
    
           try { 
               UserRepository repository = new UserRepository(cassandraSession); 
               //Create keyspace in cassandra database 
               repository.createKeyspace(); 
               //Create table in cassandra database 
               repository.createTable(); 
    
           } finally { 
               utils.close(); 
               LOGGER.info("Please delete your table after verifying the presence of the data in portal or from CQL"); 
           } 
       } 
    } 
    

运行应用程序Run the app

  1. 打开命令提示符或终端窗口。Open a command prompt or terminal window. 粘贴以下代码块。Paste the following code block.

    此代码将目录 (cd) 更改为在其中创建项目的文件夹路径。This code changes the directory (cd) to the folder path where you created the project. 接着,它将运行 mvn clean install 命令以在目标文件夹中生成 cosmosdb-cassandra-examples.jar 文件。Then, it runs the mvn clean install command to generate the cosmosdb-cassandra-examples.jar file within the target folder. 最后,它运行 Java 应用程序。Finally, it runs the Java application.

    cd cassandra-demo
    
    mvn clean install 
    
    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.

  2. 现在在 Azure 门户中,打开“数据资源管理器”以确认是否已创建键空间和表****。Now, in the Azure portal, open Data Explorer to confirm that the keyspace and table were created.

后续步骤Next steps

本教程介绍了如何使用 Java 应用程序在 Azure Cosmos DB 中创建 Cassandra API 帐户,以及创建数据库和表。In this tutorial, you've learned how to create a Cassandra API account in Azure Cosmos DB, a database, and a table by using a Java application. 你现在可以继续学习下一篇文章:You can now proceed to the next article: