Quickstart: Use Azure Cache for Redis in .NET Framework
In this quickstart, you incorporate Azure Cache for Redis into a .NET Framework app to have access to a secure, dedicated cache that is accessible from any application within Azure. You specifically use the StackExchange.Redis client with C# code in a .NET console app.
Skip to the code on GitHub
Clone the repo from Azure-Samples/azure-cache-redis-samples on GitHub.
Prerequisites
- Azure subscription - create one for free
- Visual Studio 2019
- .NET Framework 4 or higher, which is required by the StackExchange.Redis client.
Create a cache
To create a cache, sign in to the Azure portal. On the portal menu, select Create a resource.
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.
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. Select the Networking tab or select Next: Networking.
On the Networking tab, select a connectivity method to use for the cache.
Select the Advanced tab or select Next: Advanced.
On the Advanced pane, verify or select an authentication method based on the following information:
- 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.
(Optional) Select the Tags tab or select Next: Tags.
(Optional) On the Tags tab, enter a tag name and value if you want to categorize your cache resource.
Select the Review + create button.
On the Review + create tab, Azure automatically validates your configuration.
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.
Use Microsoft Entra ID authentication on your cache
Azure Redis caches, except for Enterprise and Enterprise Flash tiers, have Microsoft Entra Authentication enabled by default. Access keys are disabled by default.
Important
Microsoft recommends using Microsoft Entra ID authentication for the most secure authentication experience instead of using passwords or access keys. The authentication described in this section of the article uses access keys, which require a very high degree of trust in the application and carries risks not present when using Microsoft Entra ID. Use the approach in this document only when Microsoft Entra ID authentication is not viable.
In the Azure portal, select the cache where you'd like to use Microsoft Entra token-based authentication.
Select Authentication from the Resource menu.
Select Select member and enter the name of a valid user. The user you enter is automatically assigned Data Owner Access Policy by default when you select Save. You can also enter a managed identity or service principal to connect to your cache instance.
For information on using Microsoft Entra ID with Azure CLI, see the reference pages for identity.
Edit the App.config file and add the following contents:
<appSettings> <add key="RedisHostName" value="your_redis_cache_hostname"/>
Replace "your_Azure_Redis_hostname" with your Azure Redis host name and port numbers. For example:
cache-name.eastus.redis.azure.net:10000
for Azure Cache for Redis Enterprise, andcache-name.redis.cache.windows.net:6380
for Azure Cache for Redis services.Save the file.
Configure the cache client
In this section, you prepare the console application to use the StackExchange.Redis client for .NET.
In Visual Studio, select Tools > NuGet Package Manager > Package Manager Console, and run the following command from the Package Manager Console window.
Install-Package Microsoft.Azure.StackExchangeRedis
Once the installation is completed, the StackExchange.Redis cache client is available to use with your project.
Connect to the cache with RedisConnection
The connection to your cache is managed by the RedisConnection
class. The connection is first made in this statement from Program.cs
:
_redisConnection = await RedisConnection.InitializeAsync(redisHostName: ConfigurationManager.AppSettings["RedisHostName"].ToString());
The value of the CacheConnection appSetting is used to reference the cache connection string from the Azure portal as the password parameter.
In RedisConnection.cs
, you see the StackExchange.Redis
namespace with the using
keyword. This is needed for the RedisConnection
class.
using StackExchange.Redis;
The RedisConnection
code ensures that there is always a healthy connection to the cache by managing the ConnectionMultiplexer
instance from StackExchange.Redis
. The RedisConnection
class recreates the connection when a connection is lost and unable to reconnect automatically.
For more information, see StackExchange.Redis and the code in a GitHub repo.
Executing 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, and gives the developer flexibility in the choice of the serializer.
One simple way to serialize objects is to use the JsonConvert
serialization methods in System.text.Json
.
Add the System.text.Json
namespace to Visual Studio:
Select Tools > NuGet Package Manager > Package Manager Console.
Then, run the following command from the Package Manager Console window.
Install-Package system.text.json
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 employeeId, string name, int age)
{
Id = employeeId;
Name = name;
Age = age;
}
}
Run the sample
Press Ctrl+F5 to build and run the console app to test serialization of .NET objects.
Clean up resources
If you want to continue to use the resources you created in this article, keep the resource group.
Otherwise, if you're finished with the resources, you can delete the Azure resource group that you created to avoid charges.
Important
Deleting a resource group is irreversible. When you delete a resource group, all the resources in it 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 contains resources you want to keep, you can delete each resource individually instead of deleting the resource group.
To delete a resource group
Sign in to the Azure portal, and then select Resource groups.
Select the resource group you want to delete.
If there are many resource groups, use the Filter for any field... box, type the name of your resource group you created for this article. Select the resource group in the results list.
Select Delete resource group.
You're asked to confirm the deletion of the resource group. Type the name of your resource group to confirm, and then select Delete.
After a few moments, the resource group and all of its resources are deleted.