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 Job 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 known as keen refresh that may provide help to maintain your cache up to date with the most recent information whereas making certain responsiveness on the identical time. Whenever you allow this function, you possibly can specify a customized length to your cached information and likewise a share threshold, as proven within the code snippet beneath.
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 information is older than 50% of the cache length (i.e., after 31 seconds), FusionCache will return the cached information after which refresh the cache within the background to make sure that the cache is up to date.