Friday, December 13, 2024

You can leverage the power of FusionCache, a distributed caching solution, within your ASP.NET Core application to boost performance and scalability. To get started, you’ll need to install the FusionCache NuGet package and configure it in your Startup.cs file. “`csharp public void ConfigureServices(IServiceCollection services) { services.AddFusionCache(options => { options.ConnectionString = “connection_string”; options.Serializer = new BinarySerializer(); }); } “` Once configured, you can use the caching mechanism throughout your application. Here’s a simple example of how to store and retrieve data: “`csharp public IActionResult Index() { var cacheKey = “my_data_key”; if (!FusionCache.TryGetValue(cacheKey, out myData)) { // Cache miss: retrieve data from database or other source myData = Database.Query(); FusionCache.Set(cacheKey, myData); } return View(myData); } “` In this scenario, the data is stored in cache when it’s first retrieved, and subsequent requests will use the cached data to improve performance.


using Microsoft.AspNetCore.Mvc;

namespace FusionCacheExample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly IProductRepository _productRepository;
        private readonly IFusionCache _fusionCache;

        public ProductController(IFusionCache fusionCache, IProductRepository productRepository)
        {
            _fusionCache = fusionCache;
            _productRepository = productRepository;
        }

        [HttpGet("{productId}")]
        public async Task GetProductAsync(int productId) GetProductById(int productId)
        {
            var cacheKey = $"product_{productId}";
            var cachedProduct = await _fusionCache.GetOrSetAsync
            (cacheKey, async () =>
            {
                return await _productRepository.GetProductById(productId);
            },
            choices =>
                choices
                    .SetDuration(TimeSpan.FromMinutes(2))
                    .SetFailSafe(true)
            );
            if (cachedProduct == null)
            {
                return NotFound();
            }
            return Okay(cachedProduct);
        }
    }
}

The keen refresh mechanism for FusionCache?

FusionCache’s keen refresh feature enables users to maintain their cache up-to-date with the latest information, ensuring simultaneous responsiveness and timeliness. By permitting this feature, users will have the flexibility to customize the length of their cached data and also set a share threshold, as demonstrated in the accompanying code snippet below.


choices => choices.SetDuration(TimeSpan.FromMinutes(1))
choices => choices.SetEagerRefresh(0.5f)

The cache length has been set at a relatively short interval of one minute, while the refresh threshold for the keen feature appears to be set at approximately half that duration, which may warrant further consideration. When a fresh request lands, FusionCache checks if its cached knowledge is more than half as old as the cache itself, typically after a 31-second interval. If this threshold is exceeded, it promptly returns the cached data and simultaneously refreshes the cache in the background to guarantee timeliness.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles