Quickstart: Use Azure Cache for Redis in .NET Core
In this quickstart, you incorporate Azure Cache for Redis into a .NET Core 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 Core console app.
Skip to the code on GitHub
Clone the repo https://github.com/Azure-Samples/azure-cache-redis-samples/tree/main/quickstart/dotnet-core on GitHub.
Prerequisites
- Azure subscription - create one for free
- .NET Core SDK
Create a cache
To create a cache, sign in to the Azure portal and select Create a resource.
On the Get Started page, type Azure Cache for Redis in the search box. Then, select Create.
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.windows.net. 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. Select the Networking tab or select the Networking button at the bottom of the page.
In the Networking tab, select your connectivity method.
Select the Next: Advanced tab or select the Next: Advanced button on the bottom of the page to see the Advanced tab.
- 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, Microsoft recommends using Microsoft Entra ID with managed identities to authorize requests against your cache whenever possible. Authorization with Microsoft Entra ID and managed identities provides superior security and ease of use over Shared Key authorization. For more about using managed identities with your caches, see Use Microsoft Entra ID for cache authentication.
Select the Next: Tags tab or select the Next: Tags button at the bottom of the page.
Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.
Select Review + create. On the Review + create, Azure validates your configuration.
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.
Retrieve host name, ports, and access keys from the Azure portal
To connect your Azure Cache for Redis server, the cache client needs the host name, ports, and a key for the cache. Some clients might refer to these items by slightly different names. You can get the host name, ports, and keys from the Azure portal.
To get the access keys, select Authentication from the Resource menu. Then, select the Access keys tab.
To get the host name and ports for your cache, select Overview from the Resource menu. The host name is of the form <DNS name>.redis.cache.windows.net.
Make a note of the HOST NAME and the Primary access key. You'll use these values later to construct the CacheConnection secret.
Add a local secret for the connection string
In your command window, execute the following command to store a new secret named CacheConnection, after replacing the placeholders (including angle brackets) for your cache name and 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 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(connectionString: configuration["CacheConnection"].ToString());
In RedisConnection.cs
, you see the StackExchange.Redis
namespace has been added to the code. 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.
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 have opened any files, save them and build the app with the following command:
dotnet build
Run the app with the following command to test serialization of .NET objects:
dotnet run
Clean up resources
If you continue to use this quickstart, you can keep the resources you created and reuse them.
Otherwise, if you're finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.
Important
Deleting a resource group is irreversible and that the resource group and 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 for hosting this sample inside an existing resource group that contains resources you want to keep, you can delete each resource individually on the left instead of deleting the resource group.
To delete a resource group
Sign in to the Azure portal and select Resource groups.
In the Filter by name... textbox, type the name of your resource group. The instructions for this article used a resource group named TestResources. On your resource group in the result list, select ... then Delete resource group.
You'll be asked to confirm the deletion of the resource group. Type the name of your resource group to confirm, and select Delete.
After a few moments, the resource group and all of its contained resources are deleted.
Next steps
Pripomienky
https://aka.ms/ContentUserFeedback.
Pripravujeme: V priebehu roka 2024 postupne zrušíme službu Problémy v službe GitHub ako mechanizmus pripomienok týkajúcich sa obsahu a nahradíme ju novým systémom pripomienok. Ďalšie informácie nájdete na stránke:Odoslať a zobraziť pripomienky pre