快速入门:使用 .NET SDK 和 Azure Cosmos DB 构建 Cassandra 应用Quickstart: Build a Cassandra app with .NET SDK and Azure Cosmos DB

本快速入门介绍如何使用 .NET 和 Azure Cosmos DB Cassandra API,通过克隆 GitHub 中的示例来生成配置文件应用。This quickstart shows how to use .NET 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 是世纪互联提供的多区域分布式多模型数据库服务。Azure Cosmos DB is 21Vianet's multiple-regionally 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 multiple-region distribution and horizontal scale capabilities at the core of Azure Cosmos DB.

先决条件Prerequisites

如果没有 Azure 订阅,可在开始前创建一个 试用帐户If you don't have an Azure subscription, create a trial account before you begin.

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

  • 如果尚未安装 Visual Studio 2019,可以下载并使用免费Visual Studio 2019 Community EditionIf you don't already have Visual Studio 2019 installed, you can download and use the free Visual Studio 2019 Community Edition. 在安装 Visual Studio 的过程中,请确保启用“Azure 开发”。 Make sure that you enable Azure development during the Visual Studio setup.
  • 安装 Git 以克隆示例。Install Git to clone the example.

创建数据库帐户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 帐户名称相同的名称。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 API 应用,设置连接字符串,并运行应用。Let's clone a Cassandra API 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-dotnet-getting-started.git
    
  4. 接下来,在 Visual Studio 中打开 CassandraQuickStartSample 解决方案文件。Next, open the CassandraQuickStartSample solution file in Visual Studio.

查看代码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. 这些代码片段全部摘自安装在 C:\git-samples\azure-cosmos-db-cassandra-dotnet-getting-started\CassandraQuickStartSample 文件夹中 Program.cs 文件。The snippets are all taken from the Program.cs file installed in the C:\git-samples\azure-cosmos-db-cassandra-dotnet-getting-started\CassandraQuickStartSample folder. 否则,可以直接跳转到更新连接字符串Otherwise, you can skip ahead to Update your connection string.

  • 通过连接到 Cassandra 群集终结点初始化会话。Initialize the session by connecting to a Cassandra cluster endpoint. Azure Cosmos DB 的 Cassandra API 仅支持 TLSv1.2。The Cassandra API on Azure Cosmos DB supports only TLSv1.2.

    var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);
    options.SetHostNameResolver((ipAddress) => CassandraContactPoint);
    Cluster cluster = Cluster.Builder().WithCredentials(UserName, Password).WithPort(CassandraPort).AddContactPoint(CassandraContactPoint).WithSSL(options).Build();
    ISession session = cluster.Connect();
    
  • 创建新密钥空间。Create a new keyspace.

    session.Execute("CREATE KEYSPACE uprofile WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 };"); 
    
  • 创建新表。Create a new table.

    session.Execute("CREATE TABLE IF NOT EXISTS uprofile.user (user_id int PRIMARY KEY, user_name text, user_bcity text)");
    
  • 使用有连接到配置文件密钥空间的新会话的 IMapper 对象插入用户实体。Insert user entities by using the IMapper object with a new session that connects to the uprofile keyspace.

    mapper.Insert<User>(new User(1, "LyubovK", "Dubai"));
    
  • 通过查询获取所有用户的信息。Query to get all user's information.

    foreach (User user in mapper.Fetch<User>("Select * from user"))
    {
      Console.WriteLine(user);
    }
    
  • 通过查询获取单个用户的信息。Query to get a single user's information.

    mapper.FirstOrDefault<User>("Select * from user where user_id = ?", 3);
    

更新连接字符串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 information enables your app to communicate with your hosted database.

  1. Azure 门户中,选择“连接字符串” 。In the Azure portal, select Connection String.

    使用Use the “复制”按钮 屏幕右侧的按钮以复制“用户名”值。button on the right side of the screen to copy the USERNAME value.

    在 Azure 门户的“连接字符串”页面中查看并复制访问密钥

  2. 在 Visual Studio 中,打开 Program.cs 文件。In Visual Studio, open the Program.cs file.

  3. 粘贴门户中的“用户名”值,并覆盖第 13 行中的 <FILLME>Paste the USERNAME value from the portal over <FILLME> on line 13.

    Program.cs 的第 13 行现在应该类似Line 13 of Program.cs should now look similar to

    private const string UserName = "cosmos-db-quickstart";

  4. 返回到门户,然后复制“密码”值。Go back to portal and copy the PASSWORD value. 粘贴门户中的“密码”值,并覆盖第 14 行中的 <FILLME>Paste the PASSWORD value from the portal over <FILLME> on line 14.

    Program.cs 的第 14 行现在应该类似Line 14 of Program.cs should now look similar to

    private const string Password = "2Ggkr662ifxz2Mg...==";

  5. 返回到门户,然后复制“联系点”值。 粘贴门户中的“联系点”值,并覆盖第 15 行中的 <FILLME>Paste the CONTACT POINT value from the portal over <FILLME> on line 15.

    Program.cs 的第 15 行现在应该类似Line 15 of Program.cs should now look similar to

    private const string CassandraContactPoint = "cosmos-db-quickstarts.cassandra.cosmos.azure.cn"; // DnsName

  6. 保存 Program.cs 文件。Save the Program.cs file.

运行 .NET 应用Run the .NET app

  1. 在 Visual Studio 中,选择“工具” > “NuGet 包管理器” > “包管理器控制台” 。In Visual Studio, select Tools > NuGet Package Manager > Package Manager Console.

  2. 在命令提示符处,使用以下命令安装 .NET 驱动程序的 NuGet 包。At the command prompt, use the following command to install the .NET Driver's NuGet package.

    Install-Package CassandraCSharpDriver
    
  3. 按 CTRL + F5 运行应用程序。Press CTRL + F5 to run the application. 应用将显示在控制台窗口中。Your app displays in your console window.

    查看并验证输出

    按 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 门户中查看 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 帐户、如何使用数据资源管理器创建容器,以及如何运行 Web 应用。In this quickstart, you've learned how to create an Azure Cosmos DB account, create a container using the Data Explorer, and run a web app. 现在可以将其他数据导入 Cosmos DB 帐户。You can now import additional data to your Cosmos DB account.