Caching is essential for improving performance and scalability in modern applications. This guide shows how to use Redis caching in .NET, including how to run it on Windows using Memurai (without Docker).
π΄ What is Redis?
Redis is an in-memory data store used to cache frequently accessed data, making applications faster by reducing database calls. It serves data instantly on a cache hit and stores new data on a cache miss, improving performance and scalability.
Why use it?
β‘ Fast (RAM-based)
π Reduces DB load
π Works across multiple servers
β± Supports expiration (TTL)
π§ How It Works (Cache Aside Pattern)
Request β Check Cache β Return (if found)
β
DB β Save in Cache β Return
π¦ Required Packages (.NET)
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
dotnet add package Newtonsoft.Json
βοΈ Redis Configuration
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
options.InstanceName = "MyApp:";
});
π₯ Caching Implementation (Service Layer)
public class ProductService
{
private readonly IDistributedCache _cache;
public ProductService(IDistributedCache cache)
{
_cache = cache;
}
public async Task<List<Product>> GetProducts()
{
string cacheKey = "product_list";
var cacheData = await _cache.GetStringAsync(cacheKey);
if (cacheData != null)
{
Console.WriteLine("Data from Redis");
return JsonConvert.DeserializeObject<List<Product>>
(cacheData);
}
Console.WriteLine("Data from DB");
var data = FakeDb.GetProducts(); // Replace with real DB
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
};
await _cache.SetStringAsync( cacheKey, JsonConvert.SerializeObject(data), options );
return data;
}
}
Run Redis WITHOUT Docker (Windows)
Use Memurai:
- Install Memurai
- Start service:
Win + R β services.msc β Start "Memurai"
- Verify:
memurai-cli ping
Output: `PONG`
Runs on:localhost:6379
π³ Recommended: Use Docker
Docker (best for production)
docker run -d -p 6379:6379 redis
π Cache Invalidation (Important)
Remove cache manually:
await _cache.RemoveAsync("product_list");
Use expiration:
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
Clear all cache (dev):
memurai-cli flushall
π§ Best Practices With...
- Always set expiry
- Use meaningful keys (product_101)
- Invalidate cache on update/delete
- Avoid caching sensitive data
Top comments (0)