utilizing Microsoft.AspNetCore.Mvc;
utilizing ZiggyCreatures.Caching.Fusion;
namespace FusionCacheExample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
non-public readonly IProductRepository _productRepository;
non-public 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);
}
}
}
FusionCache features a nice characteristic referred to as keen refresh that may assist you to preserve your cache up to date with the newest knowledge whereas making certain responsiveness on the similar time. If you allow this characteristic, you possibly can specify a customized period to your cached knowledge and likewise a share threshold, as proven within the code snippet under.
choices => choices.SetDuration(TimeSpan.FromMinutes(1))
choices => choices.SetEagerRefresh(0.5f)
Word how the cache period has been set to 1 minute whereas the keen refresh threshold is about 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.