Thursday, September 19, 2024

Tips on how to work with FusionCache in ASP.NET Core


utilizing Microsoft.AspNetCore.Mvc;
utilizing ZiggyCreatures.Caching.Fusion;
namespace FusionCacheExample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        personal readonly IProductRepository _productRepository;
        personal readonly IFusionCache _fusionCache;
        public ProductController(IFusionCache fusionCache,
        IProductRepository productRepository)
        {
            _fusionCache = fusionCache;
            _productRepository = productRepository;
        }
        [HttpGet("{productId}")]
        public async Activity 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);
        }
    }
}

Assist for keen refresh in FusionCache

FusionCache features a nice function referred to as keen refresh that may make it easier to maintain your cache up to date with the most recent knowledge whereas guaranteeing responsiveness on the similar time. If you allow this function, you may specify a customized length to your cached knowledge and likewise a proportion threshold, as proven within the code snippet under.


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

Word how the cache length has been set to 1 minute whereas the keen refresh threshold is ready to 50% of the cache length. When a brand new request arrives and your cached knowledge is older than 50% of the cache length (i.e., after 31 seconds), FusionCache will return the cached knowledge after which refresh the cache within the background to make sure that the cache is up to date.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles