A Simple Example of Using a Distributed Cache (Redis) in .NET 6 with API Endpoints

In my previous post, I showed how to use a simple memory cache with .NET 6 endpoints. The cache ran in the same process as the application, so if you launched multiple instances of the application, a cache per instance would be shared.

In this example, I use a distributed memory cache with Redis. A single cache is shared across all instances of the application.

You need to have docker installed. Run Redis using -

docker run -it --rm --name my-redis -p 6379:6379 redis

Create a new Web API application and add the Microsoft.Extensions.Caching.StackExchangeRedis package.

This is the code you need to add the cache to the service collection, pass the distributed cache to the endpoint, and get/set values in the cache.

 1using Microsoft.Extensions.Caching.Distributed;
 2
 3var builder = WebApplication.CreateBuilder(args);
 4
 5// Add services to the container.
 6builder.Services.AddStackExchangeRedisCache(options =>
 7{
 8    options.Configuration = "localhost:6379"; 
 9});
10
11builder.Services.AddSingleton<Random>();
12var app = builder.Build();
13
14app.MapGet("/Inventory/{itemId}", (string itemId, IDistributedCache distributedCache, Random random) =>
15{
16    Console.WriteLine($"You requested item:{itemId}, looking in cache...");
17    string? quantity = distributedCache.GetString(itemId);
18    if(quantity != null)
19    {
20        Console.WriteLine($"Found item:{itemId}, in the cache!");
21        return Results.Ok($"Found item:{itemId}, in the cache. We have {quantity} in stock.");
22    }
23    else
24    {
25        Console.WriteLine("Could not find id:{id} in the cache! Searching the database...");
26        // Not really going to look in the database.
27        quantity = random.Next(100).ToString();
28        distributedCache.SetString(itemId, quantity, new DistributedCacheEntryOptions
29        {
30            AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10)
31        }); 
32        return Results.Ok($"Found item:{itemId} in the database. We have {quantity} in stock. Adding it to the cache now.");
33    }   
34});
35
36app.Run();

To demonstrate that the cache is shared, start up a couple of instances of the application.

dotnet run --urls "http://*:5000"
dotnet run --urls "http://*:5500"

Then in a couple of browser tabs, go to http://localhost:5000/inventory/11, and http://localhost:5500/inventory/11.

You will that the two instances of the application are sharing the same cache.

comments powered by Disqus

Related