1 回答
TA贡献1799条经验 获得超6个赞
检查您用于缓存的数据库,我的第一个猜测是实际上没有存储任何内容。
使用 IoC,正确的设置看起来像是向服务添加分布式缓存
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = _config["SQLDataProvider_Cache"];
options.SchemaName = "dbo";
options.TableName = "TestCache";
});
您可以使用两种类型的缓存策略:
(DateTimeOffSet) CacheItemPolicy.AbsoluteExpiration 在初始设置的固定时间后过期
(DateTimeOffSet) CacheItemPolicy.SlidingExpiration 自上次访问起的固定时间后过期
通常您会想要使用 SlidingExpiration 之一,但当您定义绝对时,注册将
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
IApplicationLifetime lifetime, IDistributedCache cache)
{
lifetime.ApplicationStarted.Register(() =>
{
var currentTimeUTC = DateTime.UtcNow.ToString();
var encodedCurrentTimeUTC = Encoding.UTF8.GetBytes(currentTimeUTC);
var options = new DistributedCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromHours(1));
cache.Set("cachedTimeUTC", encodedCurrentTimeUTC, options);
});
存储库本身不应包含静态成员(或仅包含记录器)。为该存储库添加接口将改进测试和模拟功能,并且成为使用 IoC 传递此信息的默认方式
public class ReportRepository : IReportRepository
{
private readonly IAppCache _cache;
private readonly ILogger _logger;
private SomeService _service;
public string ServiceUrl { get; set; }
public string RequestUri { get; set; }
public ReportRepository(IAppCache appCache, ILogger<ShowDatabase> logger, SomeService service)
{
_service = service;
_logger = logger;
_cache = appCache;
}
public async Task<List<Show>> GetShows()
{
var cacheKey = "kpi_{companyID}_{fromYear}_{fromMonth}_{toYear}_{toMonth}_{locationIDs}";
Func<Task<List<DataSet>>> reportFactory = () => PopulateReportCache();
//if you do it in DistributedCacheEntryOptions you do not need to set it here
var absoluteExpiration = DateTimeOffset.Now.AddHours(1);
var result = await _cache.GetOrAddAsync(cacheKey, reportFactory, absoluteExpiration);
return result;
}
private async Task<List<DataSet>> PopulateReportCache()
{
List<DataSet> reports = await _service.GetData(ServiceUrl, RequestUri, out result);
_logger.LogInformation($"Loaded {reports.Count} report(s)");
return reports.ToList(); //I would have guessed it returns out parameter result ...
}
}
- 1 回答
- 0 关注
- 143 浏览
添加回答
举报