這篇文章主要介紹“NetCore的緩存使用方法”,在日常操作中,相信很多人在NetCore的緩存使用方法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”NetCore的緩存使用方法”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
緩存可以減少生成內容所需的工作,從而顯著提高應用程序的性能和可伸縮性。 緩存最適用于不經常更改的 數據,生成 成本很高。 通過緩存,可以比從數據源返回的數據的副本速度快得多。 應該對應用進行編寫和測試,使其 永不 依賴于緩存的數據。
ASP.NET Core 支持多個不同的緩存。 最簡單的緩存基于 IMemoryCache。 IMemoryCache
表示存儲在 web 服務器的內存中的緩存。 在服務器場上運行的應用 (多臺服務器) 應確保會話在使用內存中緩存時處于粘滯狀態。 粘滯會話確保來自客戶端的后續請求都將發送到相同的服務器。
內存中緩存可以存儲任何對象。 分布式緩存接口僅限 byte[]
。 內存中和分布式緩存將緩存項作為鍵值對。
代碼應始終具有回退選項,以獲取數據,而 不是依賴于可用的緩存值。
緩存使用稀有資源內存,限制緩存增長:
不要 使用外部 輸入作為緩存鍵。
使用過期限制緩存增長。
使用 SetSize、Size 和 SizeLimit 限制緩存大小]。 ASP.NET Core 運行時不會根據內存 壓力限制緩存 大小。 開發人員需要限制緩存大小。
創建一個NetCore控制臺項目,進行緩存的項目演示。
控制臺項目只有一個初始化的Program.cs文件?;贜etCore進行項目編碼,每一步就是創建一個基礎模板,使用依賴注入的方式。
nuget install Microsoft.Extensions.Hosting
public static class Program { static async void Main(string[] args) { var builder = new HostBuilder().ConfigureServices((context, service) => { }); await builder.RunConsoleAsync(); } }
注入緩存服務,控制臺需要下載庫 Microsoft.Extensions.Caching.Memory
nuget install Microsoft.Extensions.Caching.Memory
public static class Program { static async void Main(string[] args) { var builder = new HostBuilder().ConfigureServices((context, service) => { service.AddMemoryCache(); service.AddScoped<CacheService>();//實際測試服務 service.AddHostedService<BackgroundJob>();//后臺執行方法 }); await builder.RunConsoleAsync(); } }
后臺服務
public class BackgroundJob : IHostedService { private readonly CacheService _cacheService; public BackgroundJob(CacheService cacheService) { _cacheService = cacheService; } public Task StartAsync(CancellationToken cancellationToken) { _cacheService.Action(); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } }
通過構造函數自動注入IMemoryCache
public class CacheService { private readonly IMemoryCache _memoryCache; public CacheService(IMemoryCache memoryCache) { _memoryCache = memoryCache; } }
Set方法根據Key設置緩存,默認緩存不過期
Get方法根據Key取出緩存
/// <summary> /// 緩存設置 /// </summary> public void BaseCache() { string cacheKey = "timestamp"; //set cache _memoryCache.Set(cacheKey, DateTime.Now.ToString()); //get cache Console.WriteLine(_memoryCache.Get(cacheKey)); }
IMemoryCache提供一些好的語法糖供開發者使用,具體內容看下方文檔
/// <summary> /// 特殊方法的使用 /// </summary> public void ActionUse() { //場景-如果緩存存在,取出。如果緩存不存在,寫入 //原始寫法 string cacheKey = "timestamp"; if (_memoryCache.Get(cacheKey) != null) { _memoryCache.Set(cacheKey, DateTime.Now.ToString()); } else { Console.WriteLine(_memoryCache.Get(cacheKey)); } //新寫法 var dataCacheValue = _memoryCache.GetOrCreate(cacheKey, entry => { return DateTime.Now.ToString(); }); Console.WriteLine(dataCacheValue); //刪除緩存 _memoryCache.Remove(cacheKey); //場景 判斷緩存是否存在的同時取出緩存數據 _memoryCache.TryGetValue(cacheKey, out string cacheValue); Console.WriteLine(cacheValue); }
設置緩存常用的方式主要是以下二種
絕對到期(指定在一個固定的時間點到期)
滑動到期(在一個時間長度內沒有被命中則過期)
組合過期 (絕對過期+滑動過期)
過期策略 5秒后過期
//set absolute cache string cacheKey = "absoluteKey"; _memoryCache.Set(cacheKey, DateTime.Now.ToString(), TimeSpan.FromSeconds(5)); //get absolute cache for (int i = 0; i < 6; i++) { Console.WriteLine(_memoryCache.Get(cacheKey)); Thread.Sleep(1000); }
過期策略 2秒的滑動過期時間,如果2秒內有訪問,過期時間延后。當2秒的區間內沒有訪問,緩存過期
//set slibing cache string cacheSlibingKey = "slibingKey"; MemoryCacheEntryOptions options = new MemoryCacheEntryOptions(); options.SlidingExpiration = TimeSpan.FromSeconds(2); _memoryCache.Set(cacheSlibingKey, DateTime.Now.ToString(), options); //get slibing cache for (int i = 0; i < 2; i++) { Console.WriteLine(_memoryCache.Get(cacheSlibingKey)); Thread.Sleep(1000); } for (int i = 0; i < 2; i++) { Thread.Sleep(2000); Console.WriteLine(_memoryCache.Get(cacheSlibingKey)); }
過期策略
6秒絕對過期+2秒滑動過期
滿足任意一個緩存都將失效
string cacheCombineKey = "combineKey"; MemoryCacheEntryOptions combineOptions = new MemoryCacheEntryOptions(); combineOptions.SlidingExpiration = TimeSpan.FromSeconds(2); combineOptions.AbsoluteExpiration = DateTime.Now.AddSeconds(6); _memoryCache.Set(cacheCombineKey, DateTime.Now.ToString(), combineOptions); //get slibing cache for (int i = 0; i < 2; i++) { Console.WriteLine(_memoryCache.Get(cacheCombineKey)); Thread.Sleep(1000); } for (int i = 0; i < 6; i++) { Thread.Sleep(2000); Console.WriteLine(i+"|" + _memoryCache.Get(cacheCombineKey)); } Console.WriteLine("------------combineKey End----------------");
當緩存更新、刪除時觸發一個回調事件,記錄緩存變化的內容。
/// <summary> /// cache狀態變化回調 /// </summary> public void CacheStateCallback() { MemoryCacheEntryOptions options = new MemoryCacheEntryOptions(); options.AbsoluteExpiration = DateTime.Now.AddSeconds(3 ); options.RegisterPostEvictionCallback(MyCallback, this); //show callback console string cacheKey = "absoluteKey"; _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options); Thread.Sleep(500); _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options); _memoryCache.Remove(cacheKey); } private static void MyCallback(object key, object value, EvictionReason reason, object state) { var message = $"Cache entry state change:{key} {value} {reason} {state}"; ((CacheService)state)._memoryCache.Set("callbackMessage", message); Console.WriteLine(message); }
設置一個緩存A 設置一個緩存B,依賴于緩存A 如果緩存A失效,緩存B也失效
/// <summary> /// 緩存依賴策略 /// </summary> public void CacheDependencyPolicy() { string DependentCTS = "DependentCTS"; string cacheKeyParent = "CacheKeys.Parent"; string cacheKeyChild = "CacheKeys.Child"; var cts = new CancellationTokenSource(); _memoryCache.Set(DependentCTS, cts); //創建一個cache策略 using (var entry = _memoryCache.CreateEntry(cacheKeyParent)) { //當前key對應的值 entry.Value = "parent" + DateTime.Now; //當前key對應的回調事件 entry.RegisterPostEvictionCallback(MyCallback, this); //基于些key創建一個依賴緩存 _memoryCache.Set(cacheKeyChild, "child" + DateTime.Now, new CancellationChangeToken(cts.Token)); } string ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent); string ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild); string callBackMsg = _memoryCache.Get<string>("callbackMessage"); Console.WriteLine("第一次獲取"); Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg); //移除parentKey _memoryCache.Get<CancellationTokenSource>(DependentCTS).Cancel(); Thread.Sleep(1000); ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent); ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild); callBackMsg = _memoryCache.Get<string>("callbackMessage"); Console.WriteLine("第二次獲取"); Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg); }
到此,關于“NetCore的緩存使用方法”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。