Redis is an in-memory data structure store that can be used as a:
Database
Cache
Message Broker
Streaming engine
In this how to, I will explain how you can configure your .NET application (C#) to make use of Redis in Azure as a distributed in-memory data store.
\uD83D\uDCD8 Configuring and using Redis
In your application install the Microsoft.Extensions.Caching.StackExchangeRedis
Depending on how you scaffolded the project, configure your dependency injection by modifying either Startup.cs or Program.cs and add the Redis dependency
As a best practice from a security perspective, you should have your connection strings, passwords, etc… stored in a secure location i.e. Key Vault, and through accessed in your application through the secrets store. In your appsettings.json modify the ConnectionStrings section and add a Redis key/value property. The “ConnectionStringRedisCache“ is an indicator for our DevOps build pipeline to replace this value with the same value from the key vault.
To get the Redis connection string, navigate to the Azure Portal where Redis is installed (we have multiple instances of redis installed in the shared resource groups NPRD-CACN-SAFSECSUR-[ENVIRONMENT]-RGP/PROD-CACN-SAFSECSUR-RGP). Select the required resource group, while still in the Overview section, filter by the redis keyword. In our case because we are in the NCD/Development environment, click on the ncdsafsecsurredis. Once inside the instance of the Redis, click on the Access keys section and then copy the Primary connection string (StackExchange.Redis), and as noted earlier, store it in a secure location.
Navigate back to your project and in your project secrets add the redis connection string. By adding it to your project secrets as opposed to your appsettings.json you avoid accidently checking it into source control, and when the project is starting and this Redis key is requested by your application, it will be automatically provided.
Now that we have the project configured to use Redis, we can inject it into our class constructor using the built in dependency injection system. I am going to inject it into our demo project’s WeatherForecastService class, and then configure the Redis key name, and create the logic to set and retrieve the values. I have also set a cache expiry time of 5 minutes.
using System.Text.Json; using Microsoft.Extensions.Caching.Distributed; namespace BlazorServer.Data { public class WeatherForecastService { private readonly IDistributedCache _cache; private string _cacheKey = "redis-demo-project-cache"; public WeatherForecastService(IDistributedCache cache) { _cache = cache; } public async Task<WeatherForecast[]> GetForecastAsync(DateTime startDate) { // Try and get the value from redis var weatherForecast = await _cache.GetStringAsync(_cacheKey); // If there is no weather data stored in the Redis cache create a new entry, otherwise get the value from the cache if (string.IsNullOrEmpty(weatherForecast)) { var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; var result = await Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = startDate.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = summaries[Random.Shared.Next(summaries.Length)] }).ToArray()); // Store data in cache and set a 5 minute expiration time await _cache.SetStringAsync( _cacheKey, JsonSerializer.Serialize(result), new DistributedCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddMinutes(5) } ); return result; } else { return JsonSerializer.Deserialize<WeatherForecast[]>(weatherForecast) ?? Array.Empty<WeatherForecast>(); } } } }
Run the project and debug your code, and you should see the cache being set and retrieved. You can also verify the key is set by accessing the console of the redis instance you are targeting, and running the following command with the key of the cache. In our sample project, we are using the key “redis-demo-project-cache”
SCAN 0 COUNT 1000 MATCH *redis-demo-project-cache*
If you want to access the value of the cache, you using the following command, depending on the type of value you have set, in our case it is considered a hash.
hgetall redis-demo-project-cache