![Asp.Net Core Caching](https://codesanitize.com/wp-content/uploads/2024/06/Asp.Net_Core_Caching-1024x576.webp)
Master Caching for Better ASP.NET Core Performance
In ASP.NET Core applications, caching is a technique for storing frequently accessed data in a temporary location for faster retrieval. This reduces the load on your database or other data sources, improving the performance and responsiveness of your web application. Covering both in-memory caching and distributed caching with examples:
1. In-Memory Caching
- Concept: In-memory caching stores frequently accessed data in the server’s RAM for faster retrieval. It’s ideal for scenarios where:
- Data changes infrequently.
- The application runs on a single server.
- Implementation: ASP.NET Core provides the
IMemoryCache
interface for in-memory caching. Here’s an example:
C#
public class ProductsController : Controller
{
private readonly IMemoryCache _cache;
public ProductsController(IMemoryCache cache)
{
_cache = cache;
}
public IActionResult GetProduct(int productId)
{
Product product;
// Check if the product is already in cache
string cacheKey = $"Product-{productId}";
product = _cache.Get<Product>(cacheKey);
if (product == null)
{
// Fetch product from database or other source
product = GetProductFromDatabase(productId);
// Set cache entry with absolute expiration or sliding expiration
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(30)); // Absolute expiration in 30 minutes
_cache.Set(cacheKey, product, cacheEntryOptions);
}
return Ok(product);
}
private Product GetProductFromDatabase(int productId)
{
// Simulate database access (replace with your actual logic)
return new Product { Id = productId, Name = $"Product {productId}" };
}
}
Explanation:
- The
IMemoryCache
instance is injected into the controller constructor. - The
GetProduct
method checks if the product with the givenproductId
exists in the cache using a uniquecacheKey
. - If not found (
product
is null), the product is retrieved from the database (GetProductFromDatabase
) and stored in the cache with an absolute expiration of 30 minutes (SetAbsoluteExpiration
). - Subsequent requests for the same product within 30 minutes will result in a cache hit, returning the cached product much faster.
2. Distributed Caching
- Concept: Distributed caching stores data across multiple servers in a cluster or cloud environment. This enables efficient caching in horizontally scaled applications and ensures data consistency across servers.
- Implementation: ASP.NET Core doesn’t provide built-in support for distributed caching. However, you can integrate with popular distributed cache providers like:
- Redis: high-performance in-memory data store – (https://redis.io/)
- SQL Server Cache: built-in caching functionality in SQL Server – (https://learn.microsoft.com/en-us/sql/relational-databases/performance-monitor/sql-server-plan-cache-object?view=sql-server-ver16)
- NCache: distributed caching solution – (https://www.alachisoft.com/ncache/)
- Example using Redis:
1. Install the StackExchange.Redis NuGet package:
Bash
dotnet add package StackExchange.Redis
2. Configure Redis connection in Startup.cs
:
C#
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedRedisCache(options =>
{
options.Configuration = "localhost:6379"; // Replace with your Redis server details
});
}
3. Inject IDistributedCache
and use it similarly to IMemoryCache
:
C#
public class ProductsController : Controller
{
private readonly IDistributedCache _cache;
public ProductsController(IDistributedCache cache)
{
_cache = cache;
}
// ... (similar code structure to in-memory caching example)
}
Considerations:
- Distributed caching introduces additional configuration and network overhead.
- Choose the right caching provider based on your performance and scalability requirements.
- Ensure cached data expiration is properly managed to maintain consistency.
By effectively utilizing in-memory and distributed caching mechanisms, you can significantly improve the performance and scalability of your ASP.NET Core applications.