Caching in .Net 8: Improving Application Performance
Introduction
In modern application development, performance is a critical factor that can make or break user experience. One of the most effective ways to enhance performance is through caching. This post will explore caching in .Net 8, its benefits, and provide practical examples to help you implement caching in your applications.
What is Caching?
Caching is the process of storing frequently accessed data in a temporary storage location, or cache, so that future requests for that data can be served faster. This reduces the need to repeatedly fetch data from the primary data source, thereby improving application performance.
Why Use Caching in .Net 8?
- Improves Performance: Reduces the time required to retrieve data.
- Reduces Load on Data Sources: Decreases the number of requests to databases or external services.
- Enhances Scalability: Helps applications handle more users and higher loads efficiently.
Types of Caching in .Net 8
.Net 8 provides several caching mechanisms, including:
- In-Memory Caching: Stores data in the memory of the application server.
- Distributed Caching: Stores data in a distributed cache, such as Redis or SQL Server, which can be shared across multiple servers.
- Response Caching: Caches HTTP responses to reduce the need for repeated processing of the same requests.
Implementing In-Memory Caching
In-memory caching is the simplest form of caching and is suitable for small to medium-sized applications. Here's how you can implement it in .Net 8:
Step 1: Install the Required Package
First, install the Microsoft.Extensions.Caching.Memory
package via NuGet.
dotnet add package Microsoft.Extensions.Caching.Memory
Step 2: Configure Caching in Startup.cs
Add the memory cache service in the ConfigureServices
method.
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
// Other service configurations
}
Step 3: Use Caching in Your Application
Inject IMemoryCache
into your service or controller and use it to cache data.
public class WeatherService
{
private readonly IMemoryCache _cache;
private readonly IHttpClientFactory _httpClientFactory;
public WeatherService(IMemoryCache cache, IHttpClientFactory httpClientFactory)
{
_cache = cache;
_httpClientFactory = httpClientFactory;
}
public async Task<WeatherForecast> GetWeatherAsync(string location)
{
if (!_cache.TryGetValue(location, out WeatherForecast forecast))
{
var client = _httpClientFactory.CreateClient();
forecast = await client.GetFromJsonAsync<WeatherForecast>($"https://api.weather.com/v3/wx/forecast?location={location}");
var cacheEntryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5),
SlidingExpiration = TimeSpan.FromMinutes(2)
};
_cache.Set(location, forecast, cacheEntryOptions);
}
return forecast;
}
}
Implementing Distributed Caching
For larger applications, distributed caching is more suitable. Here's an example using Redis:
Step 1: Install the Required Package
Install the Microsoft.Extensions.Caching.StackExchangeRedis
package via NuGet.
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
Step 2: Configure Caching in Startup.cs
Add the Redis cache service in the ConfigureServices
method.
public void ConfigureServices(IServiceCollection services)
{
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
options.InstanceName = "SampleInstance";
});
// Other service configurations
}
Step 3: Use Caching in Your Application
Inject IDistributedCache
into your service or controller and use it to cache data.
public class WeatherService
{
private readonly IDistributedCache _cache;
private readonly IHttpClientFactory _httpClientFactory;
public WeatherService(IDistributedCache cache, IHttpClientFactory httpClientFactory)
{
_cache = cache;
_httpClientFactory = httpClientFactory;
}
public async Task<WeatherForecast> GetWeatherAsync(string location)
{
var cachedForecast = await _cache.GetStringAsync(location);
if (cachedForecast == null)
{
var client = _httpClientFactory.CreateClient();
var forecast = await client.GetFromJsonAsync<WeatherForecast>($"https://api.weather.com/v3/wx/forecast?location={location}");
var cacheEntryOptions = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5),
SlidingExpiration = TimeSpan.FromMinutes(2)
};
await _cache.SetStringAsync(location, JsonSerializer.Serialize(forecast), cacheEntryOptions);
return forecast;
}
return JsonSerializer.Deserialize<WeatherForecast>(cachedForecast);
}
}
Conclusion
Caching is a powerful technique to improve the performance and scalability of your .Net 8 applications. By understanding and implementing the different types of caching, you can significantly enhance your application's responsiveness and efficiency.
Top comments (3)
Good article, thanks...
Hi Duc Dang,
Top, very nice and helpful !
Thanks for sharing.
ขอบคุณครับ