Caching in .Net 8: Improving Application Performance

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…


This content originally appeared on DEV Community and was authored by Duc Dang

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:

  1. In-Memory Caching: Stores data in the memory of the application server.
  2. Distributed Caching: Stores data in a distributed cache, such as Redis or SQL Server, which can be shared across multiple servers.
  3. 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.


This content originally appeared on DEV Community and was authored by Duc Dang


Print Share Comment Cite Upload Translate Updates
APA

Duc Dang | Sciencx (2024-08-19T16:28:00+00:00) Caching in .Net 8: Improving Application Performance. Retrieved from https://www.scien.cx/2024/08/19/caching-in-net-8-improving-application-performance/

MLA
" » Caching in .Net 8: Improving Application Performance." Duc Dang | Sciencx - Monday August 19, 2024, https://www.scien.cx/2024/08/19/caching-in-net-8-improving-application-performance/
HARVARD
Duc Dang | Sciencx Monday August 19, 2024 » Caching in .Net 8: Improving Application Performance., viewed ,<https://www.scien.cx/2024/08/19/caching-in-net-8-improving-application-performance/>
VANCOUVER
Duc Dang | Sciencx - » Caching in .Net 8: Improving Application Performance. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/19/caching-in-net-8-improving-application-performance/
CHICAGO
" » Caching in .Net 8: Improving Application Performance." Duc Dang | Sciencx - Accessed . https://www.scien.cx/2024/08/19/caching-in-net-8-improving-application-performance/
IEEE
" » Caching in .Net 8: Improving Application Performance." Duc Dang | Sciencx [Online]. Available: https://www.scien.cx/2024/08/19/caching-in-net-8-improving-application-performance/. [Accessed: ]
rf:citation
» Caching in .Net 8: Improving Application Performance | Duc Dang | Sciencx | https://www.scien.cx/2024/08/19/caching-in-net-8-improving-application-performance/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.