十年河東,十年河西,莫欺少年窮
學無止境,精益求精
ASP.NET Core 緩存Caching,.NET Core 中為我們提供了Caching 的組件。
目前Caching 組件提供了三種存儲方式。
Memory
Redis
SqlServer
學習在ASP.NET Core 中使用Caching。
Memory Caching
1.新建一個 ASP.NET Core 項目,選擇Web 應用程序,將身份驗證 改為 不進行身份驗證。
2.添加引用
Install-Package Microsoft.Extensions.Caching.Memory
3.使用
在Startup.cs 中 ConfigureServices
public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); // Add framework services. services.AddMvc(); }
然后在控制器中依賴注入、
private IMemoryCache _cache; public LongLongController(IMemoryCache memoryCache) { _cache = memoryCache; }
1、方法:TryGetValue 及 方法緩存的存取
public IActionResult Index() { string cacheKey_2 = "CacheKey"; List<string> cacheEntry; //如果緩存沒有過期,則Out測試就是緩存存儲的值,注意存放值的類型應該和Out參數一致。 var bol = _cache.TryGetValue<List<string>>(cacheKey_2, out cacheEntry); //判斷緩存是否存在 if (!bol) { List<string> lst = new List<string>() { "陳大六", "陳卧龍", "陳新宇", "劉麗", "花國鋒" }; var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(10)); _cache.Set(cacheKey_2, lst, cacheEntryOptions); } ViewBag.cacheEntry = _cache.Get(cacheKey_2); return View(); }
在TryGetValue 中,Out 參數的類型應與緩存中存儲的值的類型一致。否則TryGetValue 中的Out參數永遠為NULL。
2、設置緩存的過期時間,可采用絕對過期時間或相對過期時間兩種模式;
相對過期時間設置方式:
var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromSeconds(10));
代碼如下:

/// <summary> /// 相對過期時間十秒 如果:十秒內不間斷有人訪問,那么在訪問期間緩存不會消失。除非前后訪問時間大於十秒,緩存會消失 /// </summary> /// <returns></returns> public IActionResult Slid() { string cacheKey_2 = "SlidCache"; List<string> cacheEntry; var bol = _cache.TryGetValue<List<string>>(cacheKey_2, out cacheEntry); //判斷緩存是否存在 if (!bol) { List<string> lst = new List<string>() { "陳大六", "陳卧龍", "陳新宇", "劉麗", "花國鋒" }; var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromSeconds(10)); _cache.Set(cacheKey_2, lst, cacheEntryOptions); } ViewBag.cacheEntry = _cache.Get(cacheKey_2); return View(); }
注意上述代碼中的備注;假設我們設置一個緩存的相對過期時間為10秒,緩存由A創建,十秒中內,B進入可系統,並讀取了緩存,這時緩存的有效時間又會變成十秒,同理,只要緩存在十秒鍾內不間斷有其他人訪問,則緩存永遠不會過期。如果大於十秒,則緩存過期。
絕對過期時間設置方式:
var cacheEntryOptions = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromSeconds(10));
代碼如下:

/// <summary> /// 絕對過期時間 10秒 /// </summary> /// <returns></returns> public IActionResult Abs() { string cacheKey_2 = "SlidCache"; List<string> cacheEntry; var bol = _cache.TryGetValue<List<string>>(cacheKey_2, out cacheEntry); //判斷緩存是否存在 if (!bol) { List<string> lst = new List<string>() { "陳大六", "陳卧龍", "陳新宇", "劉麗", "花國鋒" }; var cacheEntryOptions = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromSeconds(10)); _cache.Set(cacheKey_2, lst, cacheEntryOptions); } ViewBag.cacheEntry = _cache.Get(cacheKey_2); return View(); }
絕對過期時間不管期間有沒有人訪問,在時間過后,就會過期,清空。
3、移除緩存
_cache.Remove(cacheKey_2);
移除緩存沒什么好說的,就是把緩存清空
代碼如下:

/// <summary> /// 測試移除緩存 /// </summary> /// <returns></returns> public IActionResult Remove() { //先添加緩存 string cacheKey_2 = "RemoveCache"; List<string> lst = new List<string>() { "陳大六", "陳卧龍", "陳新宇", "劉麗", "花國鋒" }; var cacheEntryOptions = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromHours(10)); _cache.Set(cacheKey_2, lst, cacheEntryOptions); //直接移除 _cache.Remove(cacheKey_2); return View(); }
4、緩存的優先級分為四種:永不過期 大於 高優先級 大於 一般優先級 大於 低優先級。
/緩存優先級 (程序壓力大時,會根據優先級自動回收)
永不過期:
var cacheEntryOptions = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.NeverRemove);
高優先級:
var HighCacheEntryOptions = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.High);
一般優先級:
var NormalCacheEntryOptions = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.Normal);
低優先級:
var LowCacheEntryOptions = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.Low);
代碼如下:

/// <summary> /// 緩存優先級 /// </summary> /// <returns></returns> public IActionResult CacheLevel() { List<string> lst = new List<string>() { "陳大六", "陳卧龍", "陳新宇", "劉麗", "花國鋒" }; //NeverRemove 最高優先級 永遠不會過期 string NeverRemove = "NeverRemove"; var cacheEntryOptions = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.NeverRemove); _cache.Set(NeverRemove, lst, cacheEntryOptions); // //High 高優先級 永遠不會過期 string High = "High"; var HighCacheEntryOptions = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.High); _cache.Set(High, lst, cacheEntryOptions); //Normal 一般的優先級 永遠不會過期 string Normal = "Normal"; var NormalCacheEntryOptions = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.Normal); _cache.Set(Normal, lst, cacheEntryOptions); //Normal 一般的優先級 永遠不會過期 string Low = "Low"; var LowCacheEntryOptions = new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.Low); _cache.Set(Low, lst, cacheEntryOptions); return View(); }
5、緩存過期后,執行回調函數,
_cache.Set(cacheKey, lst, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromSeconds(10)) .RegisterPostEvictionCallback((key, value, reason, substate) => { //調用回調函數 GetIntList(key,value,reason,substate); }));
代碼如下:

public IActionResult cacheCallback() { List<string> lst = new List<string>() { "陳大六", "陳卧龍", "陳新宇", "劉麗", "花國鋒" }; //緩存回調 10秒過期會回調 string cacheKey = "cacheKey"; _cache.Set(cacheKey, lst, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromSeconds(10)) .RegisterPostEvictionCallback((key, value, reason, substate) => { //調用回調函數 GetIntList(key,value,reason,substate); })); // return View(); } public void GetIntList(object key,object value, object reason, object substate) { List<string> lst=(List<string>)value; //說白了就是被釋放了 Console.WriteLine($"鍵{key}的緩存因:{reason}而改變。"); foreach(var item in lst) { Console.WriteLine(item); } }
6、緩存回調 根據Token過期
var cts = new CancellationTokenSource(); _cache.Set(cacheKey, lst, new MemoryCacheEntryOptions() .AddExpirationToken(new CancellationChangeToken(cts.Token)) .RegisterPostEvictionCallback((key, value, reason, substate) => { Console.WriteLine($"鍵{key}值{value}改變,因為{reason}"); })); cts.Cancel(); //執行到Cancel()方法時,會執行回調刪除
代碼如下:

public ActionResult CacheToken() { List<string> lst = new List<string>() { "陳大六", "陳卧龍", "陳新宇", "劉麗", "花國鋒" }; string cacheKey = "CacheToken"; //緩存回調 根據Token過期 var cts = new CancellationTokenSource(); _cache.Set(cacheKey, lst, new MemoryCacheEntryOptions() .AddExpirationToken(new CancellationChangeToken(cts.Token)) .RegisterPostEvictionCallback((key, value, reason, substate) => { Console.WriteLine($"鍵{key}值{value}改變,因為{reason}"); })); cts.Cancel(); //執行到Cancel()方法時,會執行回調刪除 return View(); }
7、頁面緩存、distributed-cache
Cshtml頁面代碼如下:
<distributed-cache name="mycache" expires-after="TimeSpan.FromSeconds(10)"> <p>緩存項10秒過期-LineZero</p> @DateTime.Now </distributed-cache> <distributed-cache name="mycachenew" expires-sliding="TimeSpan.FromSeconds(10)"> <p>緩存項有人訪問就不會過期,無人訪問10秒過期-LineZero</p> @DateTime.Now </distributed-cache>
這樣就能緩存標簽內的內容。
如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。
@陳卧龍的博客