using Microsoft.AspNetCore.Mvc;
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 GetProductAsync(int productId) 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);
}
}
}
The keen refresh mechanism for FusionCache?
FusionCache’s keen refresh feature enables users to maintain their cache up-to-date with the latest information, ensuring simultaneous responsiveness and timeliness. By permitting this feature, users will have the flexibility to customize the length of their cached data and also set a share threshold, as demonstrated in the accompanying code snippet below.
choices => choices.SetDuration(TimeSpan.FromMinutes(1))
choices => choices.SetEagerRefresh(0.5f)
The cache length has been set at a relatively short interval of one minute, while the refresh threshold for the keen feature appears to be set at approximately half that duration, which may warrant further consideration. When a fresh request lands, FusionCache checks if its cached knowledge is more than half as old as the cache itself, typically after a 31-second interval. If this threshold is exceeded, it promptly returns the cached data and simultaneously refreshes the cache in the background to guarantee timeliness.