How to work with FusionCache in ASP.NET Core




using Microsoft.AspNetCore.Mvc;
using ZiggyCreatures.Caching.Fusion;
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 GetProductById(int productId)
        {
            var cacheKey = $"product_{productId}";
            var cachedProduct = await _fusionCache.GetOrSetAsync
            (cacheKey, async () =>
            {
                return await _productRepository.GetProductById(productId);
            },
            options =>
                options
                    .SetDuration(TimeSpan.FromMinutes(2))
                    .SetFailSafe(true)
            );
            if (cachedProduct == null)
            {
                return NotFound();
            }
            return Ok(cachedProduct);
        }
    }
}

Support for eager refresh in FusionCache

FusionCache includes a great feature called eager refresh that can help you keep your cache updated with the latest data while ensuring responsiveness at the same time. When you enable this feature, you can specify a custom duration for your cached data and also a percentage threshold, as shown in the code snippet below.


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

Note how the cache duration has been set to 1 minute while the eager refresh threshold is set to 50% of the cache duration. When a new request arrives and your cached data is older than 50% of the cache duration (i.e., after 31 seconds), FusionCache will return the cached data and then refresh the cache in the background to ensure that the cache is updated.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img