1 回答

TA貢獻1799條經(jīng)驗 獲得超6個贊
檢查您用于緩存的數(shù)據(jù)庫,我的第一個猜測是實際上沒有存儲任何內(nèi)容。
使用 IoC,正確的設(shè)置看起來像是向服務(wù)添加分布式緩存
services.AddDistributedSqlServerCache(options =>
{
? ? options.ConnectionString = _config["SQLDataProvider_Cache"];
? ? options.SchemaName = "dbo";
? ? options.TableName = "TestCache";
});
您可以使用兩種類型的緩存策略:
(DateTimeOffSet) CacheItemPolicy.AbsoluteExpiration 在初始設(shè)置的固定時間后過期
(DateTimeOffSet) CacheItemPolicy.SlidingExpiration 自上次訪問起的固定時間后過期
通常您會想要使用 SlidingExpiration 之一,但當(dāng)您定義絕對時,注冊將
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);
? ? });
存儲庫本身不應(yīng)包含靜態(tài)成員(或僅包含記錄器)。為該存儲庫添加接口將改進測試和模擬功能,并且成為使用 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 關(guān)注
- 171 瀏覽
添加回答
舉報