แก้ไข

แชร์ผ่าน


Quickstart: Build a Cassandra app with .NET Core and Azure Cosmos DB

APPLIES TO: Cassandra

This quickstart shows how to use .NET Core and the Azure Cosmos DB API for Cassandra to build a profile app by cloning an example from GitHub. This quickstart also shows you how to use the web-based Azure portal to create an Azure Cosmos DB account.

Azure Cosmos DB is Microsoft's globally distributed multi-model database service. You can quickly create and query document, table, key-value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Azure Cosmos DB.

Prerequisites

If you don't have an Azure subscription, create an Azure free account before you begin. Alternatively, you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments.

In addition, you need:

  • Latest Visual Studio with the Azure development workload. You can get started with the free Visual Studio Community IDE. Enable the Azure development workload during Visual Studio setup.
  • Install Git to clone the example.

Create a database account

  1. From the Azure portal menu or the Home page, select Create a resource.

  2. On the New page, search for and select Azure Cosmos DB.

  3. On the Azure Cosmos DB page, select Create.

  4. On the API page, select Create under the Cassandra section.

    The API determines the type of account to create. Azure Cosmos DB provides five APIs: NoSQL for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. You must create a separate account for each API.

    Select Cassandra, because in this quickstart you are creating a table that works with the API for Cassandra.

    Learn more about the API for Cassandra.

  5. In the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos DB account.

    Setting Value Description
    Subscription Your subscription 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. For simplicity, use the same name as your Azure Cosmos DB account name.
    Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Your account URI will be cassandra.cosmos.azure.com appended to your unique account name.

    The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data.
    Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode.
    Apply Azure Cosmos DB free tier discount Apply or Do not apply With Azure Cosmos DB free tier, you will get the first 1000 RU/s and 25 GB of storage for free in an account. Learn more about free tier.
    Limit total account throughput Select to limit throughput of the account This is useful if you want to limit the total throughput of the account to a specific value.

    Note

    You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    The new account page for Azure Cosmos DB for Apache Cassandra

  6. In the Global Distribution tab, configure the following details. You can leave the default values for the purpose of this quickstart:

    Setting Value Description
    Geo-Redundancy Disable Enable or disable global distribution on your account by pairing your region with a pair region. You can add more regions to your account later.
    Multi-region Writes Disable Multi-region writes capability allows you to take advantage of the provisioned throughput for your databases and containers across the globe.
    Availability Zones Disable Availability Zones are isolated locations within an Azure region. Each zone is made up of one or more datacenters equipped with independent power, cooling, and networking.

    Note

    The following options are not available if you select Serverless as the Capacity mode:

    • Apply Free Tier Discount
    • Geo-redundancy
    • Multi-region Writes
  7. Optionally you can configure additional details in the following tabs:

    • Networking - Configure access from a virtual network.
    • Backup Policy - Configure either periodic or continuous backup policy.
    • Encryption - Use either service-managed key or a customer-managed key.
    • Tags - Tags are name/value pairs that enable you to categorize resources and view consolidated billing by applying the same tag to multiple resources and resource groups.
  8. Select Review + create.

  9. Review the account settings, and then select Create. It takes a few minutes to create the account. Wait for the portal page to display Your deployment is complete.

    The Azure portal Notifications pane

  10. Select Go to resource to go to the Azure Cosmos DB account page.

Clone the sample application

Now let's switch to working with code. Let's clone a API for Cassandra app from GitHub, set the connection string, and run it. You'll see how easily you can work with data programmatically.

  1. Open a command prompt. Create a new folder named git-samples. Then, close the command prompt.

    md "C:\git-samples"
    
  2. 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-core-getting-started.git
    
  4. 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. The snippets are all taken from the Program.cs file within async Task ProcessAsync() method, installed in the C:\git-samples\azure-cosmos-db-cassandra-dotnet-core-getting-started\CassandraQuickStart folder. Otherwise, you can skip ahead to Update your connection string.

  • Initialize the session by connecting to a Cassandra cluster endpoint. The API for Cassandra 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 = await cluster.ConnectAsync();
    
  • Drop existing keyspace if it already exists.

    await session.ExecuteAsync(new SimpleStatement("DROP KEYSPACE IF EXISTS uprofile")); 
    
  • Create a new keyspace.

    await session.ExecuteAsync(new SimpleStatement("CREATE KEYSPACE uprofile WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 };"));
    
  • Create a new table.

    await session.ExecuteAsync(new SimpleStatement("CREATE TABLE IF NOT EXISTS uprofile.user (user_id int PRIMARY KEY, user_name text, user_bcity text)"));
    
  • Insert user entities by using the IMapper object with a new session that connects to the uprofile keyspace.

    await mapper.InsertAsync<User>(new User(1, "LyubovK", "Dubai"));
    
  • Query to get all user's information.

    foreach (User user in await mapper.FetchAsync<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

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. In the Azure portal, select Connection String.

  2. Use the button on the right side of the screen to copy the USERNAME value.

    View and copy an access key in the Azure portal, Connection String page

  3. In Visual Studio, open the Program.cs file.

  4. Paste the USERNAME value from the portal over <PROVIDE> on line 13.

    Line 13 of Program.cs should now look similar to

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

    You can also paste the same value over <PROVIDE> on line 15 for the CONTACT POINT value:

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

  5. Go back to portal and copy the PASSWORD value. Paste the PASSWORD value from the portal over <PROVIDE> on line 14.

    Line 14 of Program.cs should now look similar to

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

  6. Go back to portal and copy the CONTACT POINT value. Paste the CONTACT POINT value from the portal over <PROVIDE> on line 16.

    Line 16 of Program.cs should now look similar to

    private const string CASSANDRACONTACTPOINT = "quickstart-cassandra-api.cassandra.cosmos.azure.com";

  7. Save the Program.cs file.

Run the .NET Core app

  1. In Visual Studio, select Tools > NuGet Package Manager > Package Manager Console.

  2. At the command prompt, use the following command to install the .NET Driver's NuGet package.

    Install-Package CassandraCSharpDriver
    
  3. Press CTRL + F5 to run the application. Your app displays in your console window.

    View and verify the output

    Press CTRL + C to stop execution of the program and close the console window.

  4. In the Azure portal, open Data Explorer to query, modify, and work with this new data.

    View the data in Data Explorer

Review SLAs in the Azure portal

The Azure portal monitors your Azure Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.

To review metrics and SLAs:

  1. Select Metrics in your Azure Cosmos DB account's navigation menu.

  2. Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB metrics suite

  3. Review the metrics on the other tabs.

Clean up resources

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. 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.

    Select the resource group to delete

  3. On the resource group Overview page, select Delete resource group.

    Delete the resource group

  4. In the next window, enter the name of the resource group to delete, and then select Delete.

Next steps

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. You can now import other data to your Azure Cosmos DB account.