快速入门:在 Azure Cosmos DB 中使用 Java 和 MongoDB API 创建控制台应用Quickstart: Create a console app with Java and the MongoDB API in Azure Cosmos DB

在本快速入门中,你将通过 Azure 门户创建和管理 Azure Cosmos DB for MongoDB API 帐户,并使用从 GitHub 克隆的 Java SDK 应用来添加数据。In this quickstart, you create and manage an Azure Cosmos DB for MongoDB API account from the Azure portal, and add data by using a Java SDK app cloned from GitHub. 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

  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 DB 帐户名称相同的名称。For simplicity, use the same name as your Azure Cosmos DB account name.
    帐户名Account Name 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account. 帐户 URI 将是追加到唯一帐户名称的“mongo.cosmos.azure.cn” 。Your account URI will be mongo.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 Azure Cosmos DB for Mongo DB APIAzure Cosmos DB for Mongo DB API API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据库的 Core (SQL)、适用于图形数据库的 Gremlin、适用于文档数据库的 Azure Cosmos DB for Mongo DB API、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, Azure Cosmos DB for Mongo DB API for document databases, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.

    选择“Azure Cosmos DB for Mongo DB API”,因为本快速入门将创建使用 MongoDB 的集合 。Select Azure Cosmos DB for Mongo DB API because in this quickstart you are creating a collection that works with MongoDB.

    了解有关 Azure Cosmos DB for MongoDB API 的详细信息Learn more about Azure Cosmos DB for MongoDB 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 for MongoDB 帐户已准备就绪”页。Wait for the portal to display the Congratulations! Your Azure Cosmos DB for Mongo DB API account is ready page.

    Azure 门户“通知”窗格

添加集合Add a collection

将新数据库命名为“db” ,将新集合命名为“coll” 。Name your new database db, and your new collection coll .

现在可以在 Azure 门户中使用数据资源管理器工具来创建数据库和容器。You can now use the Data Explorer tool in the Azure portal to create a database and container.

  1. 选择“数据资源管理器” “新建容器”。 > Select Data Explorer > New Container.

    “添加容器”区域显示在最右侧,可能需要向右滚动才能看到它。 The Add Container area is displayed on the far right, you may need to scroll right to see it.

    Azure 门户 >“数据资源管理器”>“添加集合”窗格

  2. 在“添加容器”页中,输入新容器的设置。 In the Add container page, enter the settings for the new container.

    设置Setting 建议的值Suggested value 说明Description
    数据库 IDDatabase ID 任务Tasks 输入 Tasks 作为新数据库的名称。Enter Tasks as the name for the new database. 数据库名称必须包含 1 到 255 个字符,不能包含 /, \\, #, ? 或尾随空格。Database names must contain from 1 through 255 characters, and they cannot contain /, \\, #, ?, or a trailing space. 选中“预配数据库吞吐量”选项,这样就可以在数据库中的所有容器之间共享预配给该数据库的吞吐量。 Check the Provision database throughput option, it allows you to share the throughput provisioned to the database across all the containers within the database. 此选项还有助于节省成本。This option also helps with cost savings.
    吞吐量Throughput 400400 将吞吐量保留为每秒 400 个请求单位 (RU/s)。Leave the throughput at 400 request units per second (RU/s). 如果想要减少延迟,以后可以增加吞吐量。If you want to reduce latency, you can scale up the throughput later.
    容器 IDContainer ID ItemsItems 输入 Items 作为新容器的名称。Enter Items as the name for your new container. 容器 ID 与数据库名称的字符要求相同。Container IDs have the same character requirements as database names.
    分区键Partition key /category/category 本文中所述的示例使用 /category 作为分区键。The sample described in this article uses /category as the partition key.

    除了前面的设置,还可以选择为容器添加“唯一键”。 In addition to the preceding settings, you can optionally add Unique keys for the container. 在此示例中,请将此字段留空。Let's leave the field empty in this example. 开发人员可以使用唯一键向数据库添加一层数据完整性。Unique keys provide developers with the ability to add a layer of data integrity to the database. 创建容器时,通过创建唯一键策略,可确保每个分区键的一个或多个值的唯一性。By creating a unique key policy while creating a container, you ensure the uniqueness of one or more values per partition key. 若要了解详细信息,请参阅 Azure Cosmos DB 中的唯一键一文。To learn more, refer to the Unique keys in Azure Cosmos DB article.

    选择“确定” 。Select OK. 数据资源管理器将显示新的数据库和容器。The Data Explorer displays the new database and container.

克隆示例应用程序Clone the sample application

现在让我们从 GitHub 克隆应用,设置连接字符串,然后运行该应用。Now let's clone an app from GitHub, set the connection string, and run it. 会看到以编程方式处理数据是多么容易。You'll see how easy it is to work with data programmatically.

  1. 打开命令提示符,新建一个名为“git-samples”的文件夹,然后关闭命令提示符。Open a command prompt, 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-mongodb-java-getting-started.git
    
  4. 然后在偏好的编辑器中打开代码。Then open the code in your favorite editor.

查看代码Review the code

此步骤是可选的。This step is optional. 如果有意了解如何使用代码创建数据库资源,可以查看以下代码片段。If you're interested in learning how the database resources are created in the code, you can review the following snippets. 否则,可以直接跳转到更新连接字符串Otherwise, you can skip ahead to Update your connection string.

以下代码片段全部摘自 Program.java 文件。The following snippets are all taken from the Program.java file.

此控制台应用使用 MongoDB Java 驱动程序This console app uses the MongoDB Java driver.

  • 此时会对 DocumentClient 进行初始化。The DocumentClient is initialized.

    MongoClientURI uri = new MongoClientURI("FILLME");`
    
    MongoClient mongoClient = new MongoClient(uri);            
    
  • 会创建新数据库和集合。A new database and collection are created.

    MongoDatabase database = mongoClient.getDatabase("db");
    
    MongoCollection<Document> collection = database.getCollection("coll");
    
  • 使用 MongoCollection.insertOne 插入一些文档Some documents are inserted using MongoCollection.insertOne

    Document document = new Document("fruit", "apple")
    collection.insertOne(document);
    
  • 使用 MongoCollection.find 执行一些查询Some queries are performed using MongoCollection.find

    Document queryResult = collection.find(Filters.eq("fruit", "apple")).first();
    System.out.println(queryResult.toJson());       
    

更新连接字符串Update your connection string

现在返回到 Azure 门户,获取连接字符串信息,并将其复制到应用。Now go back to the Azure portal to get your connection string information and copy it into the app.

  1. 从你的 Azure Cosmos DB 帐户中,选择“快速启动”,选择“Java”,然后将连接字符串复制到剪贴板。 From your Azure Cosmos DB account, select Quick Start, select Java, then copy the connection string to your clipboard.

  2. 打开 Program.java 文件,将 MongoClientURI 构造函数的参数替换为该连接字符串。Open the Program.java file, replace the argument to the MongoClientURI constructor with the connection string. 现已使用与 Azure Cosmos DB 进行通信所需的所有信息更新应用。You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

运行控制台应用Run the console app

  1. 在终端中运行 mvn package,安装所需的 npm 模块Run mvn package in a terminal to install required npm modules

  2. 在终端中运行 mvn exec:java -D exec.mainClass=GetStarted.Program,启动 Java 应用程序。Run mvn exec:java -D exec.mainClass=GetStarted.Program in a terminal to start your Java application.

现在可以使用 Robomongo / Studio 3T 来查询、修改和处理此新数据。You can now use Robomongo / Studio 3T 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

执行完应用和 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

在本快速入门中,你已了解了如何创建 Azure Cosmos DB API for Mongo DB 帐户,使用数据资源管理器创建数据库和容器,以及使用 Java 控制台应用来添加数据。In this quickstart, you learned how to create an Azure Cosmos DB API for Mongo DB account, add a database and container using Data Explorer, and add data using a Java console app. 现在可以向你的 Cosmos 数据库导入更多数据。You can now import additional data to your Cosmos database.