🚀 Redis Cache in .NET Core: A Beginner’s End-to-End Guide!

Transforming your app into a performance powerhouse!

DotNet Full Stack Dev
5 min readOct 25, 2024

Imagine your app is an awesome, bustling marketplace, and every user wants the freshest data immediately. But every time your app reaches out to the database for the same info, it gets slower and slower. Enter Redis caching — the secret weapon for speeding up your .NET Core app and keeping your data retrieval super snappy! Let’s explore this powerful caching solution from scratch, building a blazing-fast Redis-powered app in .NET Core, step by step. Ready? Let’s jump in!

đź“ŚExplore more at: https://dotnet-fullstack-dev.blogspot.com/
🌟 Clapping would be appreciated! 🚀

đź“Ś What is Redis? Why Use It?

Redis (Remote Dictionary Server) is a lightning-fast in-memory data store. Think of it as a hyper-fast, super-scalable key-value storage that holds data in memory instead of on disk, making it perfect for caching. In simple terms:

  1. Faster Data Access: Redis stores data in memory, making it quick to retrieve.
  2. Persistent Options: Redis can be configured to write to disk, preserving data even after a server reboot.
  3. Distributed Cache: Redis works across multiple servers, making it scalable and fault-tolerant.

đź›  Step 1: Setting Up Redis Locally

First things first, you’ll need Redis installed. If you’re on:

  • Windows: You can use Docker Desktop to spin up Redis quickly.
  • Mac/Linux: Use Docker as well, or download Redis directly from redis.io.

To get Redis running with Docker, simply use:

docker run --name my-redis -p 6379:6379 -d redis

Now, Redis will be up and listening on port 6379.

🏗️ Step 2: Add Redis Cache to Your .NET Core App

Fire up a new or existing .NET Core app, and let’s add Redis caching in just a few steps.

Add the Redis NuGet Package
Open your project, then in the terminal or package manager console, run:

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
  • This package provides all the Redis goodies to set up caching in your app.

Configure Redis in appsettings.json

  • Add the Redis configuration in your appsettings.json file. It should look something like this:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}

Set up Redis Cache in Startup.cs

Now, let’s wire up Redis in your Startup.cs configuration.

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = Configuration.GetConnectionString("Redis");
options.InstanceName = "SampleApp_"; // Optional prefix for cache keys
});

services.AddControllers();
}
}

🎉 That’s it! Redis caching is now set up and ready to use.

🔥 Step 3: Using Redis Cache in Your App

Now that we’ve set up Redis, let’s create a sample ItemService that leverages it for caching. This service will cache data the first time it’s fetched and retrieve it from Redis on subsequent calls, making your app’s performance skyrocket 🚀.

Create a Simple ItemService with Caching

Here’s how we’ll do it: check if the data exists in the cache. If it does, return it. If not, fetch it from the database (or a simulation of it), cache it, and return it.

Create a Service Interface:

public interface IItemService
{
Task<Item> GetItemAsync(int itemId);
}

Implement Caching in ItemService:

public class ItemService : IItemService
{
private readonly IDistributedCache _cache;
private readonly TimeSpan _cacheExpiry = TimeSpan.FromMinutes(5);

public ItemService(IDistributedCache cache)
{
_cache = cache;
}

public async Task<Item> GetItemAsync(int itemId)
{
string cacheKey = $"Item_{itemId}";

// Step 1: Try to get the item from Redis cache
var cachedItem = await _cache.GetStringAsync(cacheKey);
if (cachedItem != null)
{
Console.WriteLine("âś… Item retrieved from cache!");
return JsonConvert.DeserializeObject<Item>(cachedItem);
}

// Step 2: Simulate database fetch (or real DB call in a production app)
var item = await FetchItemFromDatabase(itemId);

// Step 3: Cache the item in Redis
await _cache.SetStringAsync(
cacheKey,
JsonConvert.SerializeObject(item),
new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = _cacheExpiry }
);

Console.WriteLine("🔄 Item added to cache.");
return item;
}

private Task<Item> FetchItemFromDatabase(int itemId)
{
// Simulating a database call
return Task.FromResult(new Item { Id = itemId, Name = "Sample Item", Description = "A cached item." });
}
}

Now we have our data caching in Redis! The first time you fetch an item, it will store it in Redis for quick retrieval next time. This greatly reduces database hits, especially on frequently accessed data.

Sample Item Model

public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}

🔄 Step 4: Set Expiration and Sliding Expiration Policies

Sometimes, you don’t want your cache to live forever. Redis in .NET Core offers flexible expiration options to keep data fresh and up-to-date.

  1. Absolute Expiration: Removes data after a fixed time.
  2. Sliding Expiration: Resets expiration every time the data is accessed.

Update the SetStringAsync method to set sliding expiration options:

await _cache.SetStringAsync(
cacheKey,
JsonConvert.SerializeObject(item),
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),
SlidingExpiration = TimeSpan.FromMinutes(2) // Resets on access
}
);

With these settings, your cache remains fresh as long as users are actively accessing it.

⚙️ Step 5: Test It Out!

Time to test our Redis caching! Fire up your app and use the ItemService to retrieve items. On the first call, data will be retrieved from the “database,” and on subsequent calls, it’ll come directly from Redis.

Add a simple controller to test the cache:

[ApiController]
[Route("api/items")]
public class ItemsController : ControllerBase
{
private readonly IItemService _itemService;

public ItemsController(IItemService itemService)
{
_itemService = itemService;
}

[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var item = await _itemService.GetItemAsync(id);
return Ok(item);
}
}

Start your application, navigate to /api/items/{id}, and watch Redis do its thing. Check the console for messages that show whether data is served from the cache or the database!

🚨 Pro Tips for Redis Caching Success

  1. Key Naming: Use unique, descriptive key names, especially if multiple services share the cache. Example: User_{userId}, Product_{productId}.
  2. Monitor Cache: Keep an eye on Redis usage to avoid cache overflow. You can use Redis monitoring tools or cloud dashboards if you’re using a managed Redis service.
  3. Data Invalidation: For rapidly changing data, consider a strategy to invalidate or update cache entries to prevent stale data.
  4. Scaling Redis: For high-traffic apps, consider Redis clustering or using managed services like Amazon ElastiCache.

🎉 Conclusion: Supercharge Your .NET Core App with Redis

And there you have it! Redis cache is a powerful tool for improving the speed and performance of your .NET Core apps. By reducing the load on your database and delivering data quickly, you’re giving users a smooth, fast experience and helping your app handle more traffic with ease.

With Redis, you’re not just caching; you’re transforming your app into a performance powerhouse! Give it a try, and watch your app’s speed soar 🚀

--

--

DotNet Full Stack Dev
DotNet Full Stack Dev

Written by DotNet Full Stack Dev

Join me to master .NET Full Stack Development & boost your skills by 1% daily with insights, examples, and techniques! https://dotnet-fullstack-dev.blogspot.com

No responses yet