Rediger

Del via


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

In this quickstart, you incorporate Azure Cache for Redis into a .NET Core 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 Core console app.

Skip to the code

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 sample code, see the .NET Core quickstart sample on GitHub.

Prerequisites

Create a cache

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

    Sceenshot that shows the Create a resource option highlighted on the left navigation pane in the Azure portal.

  2. On the Get Started pane, enter Azure Cache for Redis in the search bar. In the search results, find Azure Cache for Redis, and then select Create.

    Screenshot that shows Azure Marketplace with Azure Cache for Redis in the search box, and the Create button is highlighted.

  3. On the New Redis Cache pane, on the Basics tab, configure the following settings for your cache:

    Setting Action Description
    Subscription Select your Azure subscription. The subscription to use to create the new instance of Azure Cache for Redis.
    Resource group Select a resource group, or select Create new and enter a new resource group name. A 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 of 1 to 63 characters that contains only numbers, letters, and hyphens. The name must start and end with a number or letter, and it can't contain consecutive hyphens. Your cache instance's host name is \<DNS name>.redis.cache.windows.net.
    Location Select a location. An Azure region that is near other services that use your cache.
    Cache SKU Select a SKU. The SKU determines the size, performance, and feature parameters that are available for the cache. For more information, see Azure Cache for Redis overview.
    Cache size Select a cache size. For more information, see Azure Cache for Redis overview.
  4. Select the Networking tab or select Next: Networking.

  5. On the Networking tab, select a connectivity method to use for the cache.

  6. Select the Advanced tab or select Next: Advanced.

  7. On the Advanced pane, verify or select an authentication method based on the following information:

    Screenshot showing the Advanced pane and the available options to select.

    • By default, for a new Basic, Standard, or Premium cache, Microsoft Entra Authentication is enabled and Access Keys Authentication is disabled.
    • For Basic or Standard caches, you can choose the selection for a non-TLS port.
    • For Standard and Premium caches, you can choose to enable availability zones. You can't disable availability zones after the cache is created.
    • For a Premium cache, configure the settings for non-TLS port, clustering, managed identity, and data persistence.

    Important

    For optimal security, we recommend that you use Microsoft Entra ID with managed identities to authorize requests against your cache if possible. Authorization by using Microsoft Entra ID and managed identities provides superior security and ease of use over shared access key authorization. For more information about using managed identities with your cache, see Use Microsoft Entra ID for cache authentication.

  8. (Optional) Select the Tags tab or select Next: Tags.

  9. (Optional) On the Tags tab, enter a tag name and value if you want to categorize your cache resource.

  10. Select the Review + create button.

    On the Review + create tab, Azure automatically validates your configuration.

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

A new cache deployment occurs over several minutes. You can monitor the progress of the deployment on the Azure Cache for Redis Overview pane. When Status displays 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.windows.net.
    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.

Make a note of the values for HOST NAME and the Primary access key. You use these values later to construct the CacheConnection secret.

Add a local secret for the connection string

In your Command Prompt window, execute the following command to store a new secret named CacheConnection. Replace the placeholders (including angle brackets) with your cache name (<cache name>) and primary access key (<primary-access-key>):

dotnet user-secrets set CacheConnection "<cache name>.redis.cache.windows.net,abortConnect=false,ssl=true,allowAdmin=true,password=<primary-access-key>"

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: configuration["CacheConnection"].ToString());

In RedisConnection.cs, the StackExchange.Redis namespace is added to the code. The namespace is required for the RedisConnection class.

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}");
    }

You can store and retrieve cache items by using the StringSetAsync and StringGetAsync methods.

In the example, you can see the Message key is set to a 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 in string format. The strings can contain many types of data, including serialized binary data. You can use serialized binary data when you store .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.

The .NET object serialization is the responsibility of the application developer. The object serialization gives the developer flexibility in their choice of the serializer.

The following Employee class was defined in Program.cs so that the sample could also 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 id, string name, int age)
        {
            Id = id;
            Name = name;
            Age = age;
        }
    }

Run the sample

If you opened any files, save the files. Then, build the app by using the following command:

dotnet build

To test serialization of .NET objects, run this command:

dotnet run

Screenshot that shows a console test 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.