Redis Cache in .NET
VzlDev
Posted on March 18, 2024
Hello guys!
Today I'll demonstrate how to implement Redis Cache in a .NET project.
What is Redis Cache?
Redis is an open source (BSD licensed), in-memory data structure store that can be used as a database, cache, message broker, and streaming engine.
Why Redis?
All Redis data resides in memory, which enables low latency and high throughput data access. Unlike traditional databases, In-memory data stores don’t require a trip to disk, reducing engine latency to microseconds. Because of this, in-memory data stores can support an order of magnitude more operations and faster response times.
Easy to use.
High availability and scalability.
Open Source.
Flexible data structures.
Step 1
You need to configure your Redis server. For that you can download and run an image of Redis in a docker container.
Step 2
Once your Redis server is up and running you need to install the following nuget package
Microsoft.Extensions.Caching.StackExchangeRedis
Step 3
On the ConnectionStrings section of the appsettings.json file, add the following entry
"ConnectionStrings": {
"Redis" : "localhost:6379"
},
Step 4
Then you need to configure your connection to the Redis server in the Program.cs
file
builder.Services.AddStackExchangeRedisCache(redisOptions =>
{
string connection = builder.Configuration.GetConnectionString("Redis");
redisOptions.Configuration = connection;
});
Step 5
On your controller, you'll need to inject IDistributedCache
via Dependency Injection.
private readonly IDistributedCache? _cache;
public TvShowsController(TvShowContext context, IDistributedCache cache)
{
_context = context;
_cache = cache;
}
Step 6
Finally is time to store and retrieve values to and from your Redis Cache.
[HttpGet]
public ActionResult<IEnumerable<TvShow>> GetTvShows()
{
string cachedData = _cache.GetString("cachedData");
if (string.IsNullOrEmpty(cachedData))
{
var tvShows = _context.TvShows.ToList();
string serializedObject = JsonConvert.SerializeObject(tvShows);
_cache.SetString("cachedData", serializedObject, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
return tvShows;
}
return JsonConvert.DeserializeObject<List<TvShow>>(cachedData);
}
I hope you liked it, stay tuned for more!
Posted on March 18, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.