Quickstart: Use Azure Cache for Redis with a .NET app

In this quickstart, you incorporate Azure Cache for Redis into a .NET app for access to a secure, dedicated cache that is accessible from any application in Azure. You specifically use the StackExchange.Redis client with C# code in a .NET console app.

Skip to the code on GitHub

This article describes how to modify the code for a sample app to create a working app that connects to Azure Cache for Redis.

If you want to go straight to the code, see the .NET quickstart sample on GitHub.

Prerequisites

Create a cache

  1. To create a cache, sign in to the Azure portal and select Create a resource.

    Create a resource is highlighted in the left navigation pane.

  2. On the Get Started page, type Azure Cache for Redis in the search box. Then, select Create.

    Screenshot of the Azure Marketplace with Azure Cache for Redis in the search box and create is highlighted with a red box.

  3. On the New Redis Cache page, configure the settings for your cache.

    Setting Choose a value Description
    Subscription Drop down and select your subscription. The subscription under which to create this new Azure Cache for Redis instance.
    Resource group Drop down and select a resource group, or select Create new and enter a new resource group name. Name for the resource group in which to create your cache and other resources. By putting all your app resources in one resource group, you can easily manage or delete them together.
    DNS name Enter a unique name. The cache name must be a string between 1 and 63 characters that contain only numbers, letters, or hyphens. The name must start and end with a number or letter, and can't contain consecutive hyphens. Your cache instance's host name is <DNS name>.redis.cache.chinacloudapi.cn.
    Location Drop down and select a location. Select a region near other services that use your cache.
    Cache SKU Drop down and select a SKU. The SKU determines the size, performance, and features parameters that are available for the cache. For more information, see Azure Cache for Redis Overview.
    Cache size Drop down and select a size of your cache For more information, see Azure Cache for Redis Overview.
  4. Select the Networking tab or select the Networking button at the bottom of the page.

  5. In the Networking tab, select your connectivity method.

  6. Select the Next: Advanced tab or select the Next: Advanced button on the bottom of the page to see the Advanced tab.

    Screenshot showing the Advanced tab in the working pane and the available option to select.

    • For Basic or Standard caches, toggle the selection for a non-TLS port. You can also select if you want to enable Microsoft Entra Authentication.
    • For a Premium cache, configure the settings for non-TLS port, clustering, managed identity, and data persistence. You can also select if you want to enable Microsoft Entra Authentication.
  7. Select the Next: Tags tab or select the Next: Tags button at the bottom of the page.

  8. Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.

  9. Select Review + create. You're taken to the Review + create tab where Azure validates your configuration.

  10. After the green Validation passed message appears, select Create.

It takes a while for a cache to create. You can monitor progress on the Azure Cache for Redis Overview page. When Status shows as Running, the cache is ready to use.

Get the host name, ports, and access key

To connect to your Azure Cache for Redis server, the cache client needs the cache's host name, ports, and an access key. Some clients might refer to these items by using slightly different names. You can get the host name, ports, and keys in the Azure portal.

  • To get an access key for your cache:

    1. In the Azure portal, go to your cache.
    2. On the service menu, under Settings, select Authentication.
    3. On the Authentication pane, select the Access keys tab.
    4. To copy the value for an access key, select the Copy icon in the key field.

    Screenshot that shows how to find and copy an access key for an instance of Azure Cache for Redis.

  • To get the host name and ports for your cache:

    1. In the Azure portal, go to your cache.
    2. On the service menu, select Overview.
    3. Under Essentials, for Host name, select the Copy icon to copy the host name value. The host name value has the form <DNS name>.redis.cache.chinacloudapi.cn.
    4. For Ports, select the Copy icon to copy the port values.

    Screenshot that shows how to find and copy the host name and ports for an instance of Azure Cache for Redis.

  1. Create a file on your computer named CacheSecrets.config. Place it in the *C:\AppSecrets* folder.

  2. Edit the CacheSecrets.config file and add the following contents:

    <appSettings>
        <add key="CacheConnection" value="<host-name>,abortConnect=false,ssl=true,allowAdmin=true,password=<access-key>"/>
    </appSettings>
    
    • Replace <host-name> with your cache host name.

    • Replace <access-key> with the primary key for your cache.

  3. Save the file.

Configure the cache client

In this section, you prepare the console application to use the StackExchange.Redis client for .NET.

  1. In Visual Studio, select Tools > NuGet Package Manager > Package Manager Console. Run the following command in the Package Manager Console window:

    Install-Package StackExchange.Redis
    
  2. When the installation is finished, the StackExchange.Redis cache client is available to use with your project.

Connect to the Secrets cache

In Visual Studio, open your App.config file to verify it contains an appSettings file attribute that references the CacheSecrets.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>

    <appSettings file="C:\AppSecrets\CacheSecrets.config"></appSettings>
</configuration>

Never store credentials in your source code. To keep this sample simple, we use an external secrets config file. A better approach would be to use Azure Key Vault with certificates.

Connect to the cache by using RedisConnection

The connection to your cache is managed by the RedisConnection class. First, make the connection in this statement in Program.cs:

     _redisConnection = await RedisConnection.InitializeAsync(connectionString: ConfigurationManager.AppSettings["CacheConnection"].ToString());


The value of the CacheConnection app setting is used to reference the cache connection string from the Azure portal as the password parameter.

In RedisConnection.cs, the StackExchange.Redis namespace appears as a using statement that the RedisConnection class requires:

using StackExchange.Redis;

The RedisConnection class code ensures that there's always a healthy connection to the cache. The connection is managed by the ConnectionMultiplexer instance from StackExchange.Redis. The RedisConnection class re-creates the connection when a connection is lost and can't reconnect automatically.

For more information, see StackExchange.Redis and the code in the StackExchange.Redis GitHub repo.

Execute cache commands

In Program.cs, you can see the following code for the RunRedisCommandsAsync method in the Program class for the console application:

private static async Task RunRedisCommandsAsync(string prefix)
    {
        // Simple PING command
        Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: PING");
        RedisResult pingResult = await _redisConnection.BasicRetryAsync(async (db) => await db.ExecuteAsync("PING"));
        Console.WriteLine($"{prefix}: Cache response: {pingResult}");

        // Simple get and put of integral data types into the cache
        string key = "Message";
        string value = "Hello! The cache is working from a .NET console app!";

        Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: GET {key} via StringGetAsync()");
        RedisValue getMessageResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringGetAsync(key));
        Console.WriteLine($"{prefix}: Cache response: {getMessageResult}");

        Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: SET {key} \"{value}\" via StringSetAsync()");
        bool stringSetResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringSetAsync(key, value));
        Console.WriteLine($"{prefix}: Cache response: {stringSetResult}");

        Console.WriteLine($"{Environment.NewLine}{prefix}: Cache command: GET {key} via StringGetAsync()");
        getMessageResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringGetAsync(key));
        Console.WriteLine($"{prefix}: Cache response: {getMessageResult}");

        // Store serialized object to cache
        Employee e007 = new Employee("007", "Davide Columbo", 100);
        stringSetResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringSetAsync("e007", JsonSerializer.Serialize(e007)));
        Console.WriteLine($"{Environment.NewLine}{prefix}: Cache response from storing serialized Employee object: {stringSetResult}");

        // Retrieve serialized object from cache
        getMessageResult = await _redisConnection.BasicRetryAsync(async (db) => await db.StringGetAsync("e007"));
        Employee e007FromCache = JsonSerializer.Deserialize<Employee>(getMessageResult);
        Console.WriteLine($"{prefix}: Deserialized Employee .NET object:{Environment.NewLine}");
        Console.WriteLine($"{prefix}: Employee.Name : {e007FromCache.Name}");
        Console.WriteLine($"{prefix}: Employee.Id   : {e007FromCache.Id}");
        Console.WriteLine($"{prefix}: Employee.Age  : {e007FromCache.Age}{Environment.NewLine}");
    }


Cache items can be stored and retrieved by using the StringSetAsync and StringGetAsync methods.

In the example, you can see the Message key is set to value. The app updated that cached value. The app also executed the PING and command.

Work with .NET objects in the cache

The Redis server stores most data as strings, but these strings can contain many types of data, including serialized binary data, which can be used when storing .NET objects in the cache.

Azure Cache for Redis can cache both .NET objects and primitive data types, but before a .NET object can be cached, it must be serialized.

This .NET object serialization is the responsibility of the application developer. You have some flexibility in your choice of the serializer.

A simple way to serialize objects is to use the JsonConvert serialization methods in System.text.Json.

Add the System.text.Json namespace in Visual Studio:

  1. Select Tools > NuGet Package Manager > Package Manager Console*.

  2. Then, run the following command in the Package Manager Console window:

    Install-Package system.text.json
    

The following Employee class was defined in Program.cs so that the sample can show how to get and set a serialized object:

class Employee
{
    public string Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public Employee(string employeeId, string name, int age)
    {
        Id = employeeId;
        Name = name;
        Age = age;
    }
}

Run the sample

To build and run the console app to test serialization of .NET objects, select Ctrl+F5.

Screenshot that shows the console app completed.

Clean up resources

If you want to continue to use the resources you created in this article, keep the resource group.

Otherwise, to avoid charges related to the resources, if you're finished using the resources, you can delete the Azure resource group that you created.

Warning

Deleting a resource group is irreversible. When you delete a resource group, all the resources in the resource group are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources. If you created the resources inside an existing resource group that has resources you want to keep, you can delete each resource individually instead of deleting the resource group.

Delete a resource group

  1. Sign in to the Azure portal, and then select Resource groups.

  2. Select the resource group to delete.

    If there are many resource groups, in Filter for any field, enter the name of the resource group you created to complete this article. In the list of search results, select the resource group.

    Screenshot that shows a list of resource groups to choose from to delete.

  3. Select Delete resource group.

  4. In the Delete a resource group pane, enter the name of your resource group to confirm, and then select Delete.

    Screenshot that shows a box that requires entering the resource name to confirm deletion.

Within a few moments, the resource group and all of its resources are deleted.