Methods 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 characteristic known as keen refresh that may provide help to maintain your cache up to date with the most recent knowledge whereas making certain responsiveness on the similar time. Whenever you allow this characteristic, you may specify a customized period to your cached knowledge and in addition a proportion threshold, as proven within the code snippet beneath.


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

Notice how the cache period has been set to 1 minute whereas the keen refresh threshold is ready to 50% of the cache period. When a brand new request arrives and your cached knowledge is older than 50% of the cache period (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.

Leave a Reply

Your email address will not be published. Required fields are marked *