網站首頁 編程語言 正文
最近有個需求需要定時清理服務器上所有的緩存。本來以為很簡單的調用一下 MemoryCache.Clear 方法就完事了。誰知道 MemoryCache 類以及 IMemoryCache 擴展方法都沒有 Clear 方法。這可給難住了,于是想找到所有的 Keys 來一個個 Remove ,誰知道居然也沒有獲取所有 Key 的方法。于是研究了一下 ,找到一些方法,下面介紹兩個方法:
自定義 CacheWrapper 包裝類
MemoryCache 構造 Entry 的時候支持傳入 CancellationChangeToken 對象,當 CancellationChangeToken.Cancel 觸發的時候會自動使該對象過期。那么我們只要對 MemoryCache 類包裝一下很容易實現一個自己的 Cache 類。
public class CacheWrapper { private readonly IMemoryCache _memoryCache; private CancellationTokenSource _resetCacheToken = new(); public CacheWrapper(IMemoryCache memoryCache) { _memoryCache = memoryCache; } public void Add(object key, object value, MemoryCacheEntryOptions memoryCacheEntryOptions) { using var entry = _memoryCache.CreateEntry(key); entry.SetOptions(memoryCacheEntryOptions); entry.Value = value; // add an expiration token that allows us to clear the entire cache with a single method call entry.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); } public object Get(object key) { return _memoryCache.Get(key); } public void Remove(object key) { _memoryCache.Remove(key); } public void Clear() { _resetCacheToken.Cancel(); // this triggers the CancellationChangeToken to expire every item from cache _resetCacheToken.Dispose(); // dispose the current cancellation token source and create a new one _resetCacheToken = new CancellationTokenSource(); } }
然后單元測試測試一下:
[TestMethod()] public void ClearTest() { var memCache = new MemoryCache(new MemoryCacheOptions()); var wrapper = new CacheWrapper(memCache); for (int i = 0; i < 10; i++) { wrapper.Add(i.ToString(), new object(), new MemoryCacheEntryOptions()); } Assert.IsNotNull(wrapper.Get("1")); Assert.IsNotNull(wrapper.Get("9")); wrapper.Clear(); for (int i = 0; i < 10; i++) { Assert.IsNull(wrapper.Get(i.ToString())); } for (int i = 0; i < 10; i++) { wrapper.Add(i.ToString(), new object(), new MemoryCacheEntryOptions()); } Assert.IsNotNull(wrapper.Get("1")); Assert.IsNotNull(wrapper.Get("9")); wrapper.Clear(); for (int i = 0; i < 10; i++) { Assert.IsNull(wrapper.Get(i.ToString())); } }
測試通過。
Compact 方法
以上 CacheWrapper 類雖然可以實現我們想要的功能,但是對于原來的程序有侵入,需要使用 CacheWrapper 類替換默認的 MemoryCache 類,不是太好。于是不死心繼續研究,后來直接看了 MemoryCache 的代碼(源碼在這),開源真香。發現 MemoryCache 有個 Compact 方法好像在干刪除的勾當。也怪我英文不好,這單詞是壓縮的意思,居然才發現。。。。于是我們的清除所有對象的需求不就輕而易舉了么?
/// Remove at least the given percentage (0.10 for 10%) of the total entries (or estimated memory?), according to the following policy: /// 1. Remove all expired items. /// 2. Bucket by CacheItemPriority. /// 3. Least recently used objects. /// ?. Items with the soonest absolute expiration. /// ?. Items with the soonest sliding expiration. /// ?. Larger objects - estimated by object graph size, inaccurate. MemoryCache.Compact(double percentage);
Compact 方法會對緩存的對象進行壓縮,參數是個double,0.1 表示壓縮 10% ,那么傳 1.0 就是壓縮 100%,那不就是 Clear All 么。所以我可以使用 Compact(1.0) 來清除所有的緩存對象。單元測試跑一下:
[TestMethod()] public void CompactTest() { var memCache = new MemoryCache(new MemoryCacheOptions()); for (int i = 0; i < 10; i++) { memCache.Set(i.ToString(), new object(), new MemoryCacheEntryOptions()); } Assert.IsNotNull(memCache.Get("1")); Assert.IsNotNull(memCache.Get("9")); memCache.Compact(1); for (int i = 0; i < 10; i++) { Assert.IsNull(memCache.Get(i.ToString())); } for (int i = 0; i < 10; i++) { memCache.Set(i.ToString(), new object(), new MemoryCacheEntryOptions()); } Assert.IsNotNull(memCache.Get("1")); Assert.IsNotNull(memCache.Get("9")); memCache.Compact(1); for (int i = 0; i < 10; i++) { Assert.IsNull(memCache.Get(i.ToString())); } }
完美通過。
這里簡單介紹下 Compact 方法。根據注釋它會按照已下優先級刪除對象:
- 過期的對象
- CacheItemPriority 設置的優先級,等級越高越不容易被刪除
- 最近最少被使用的對象
- 絕對過期時間
- 滑動過期時間
- 大對象
原文鏈接:https://www.cnblogs.com/kklldog/p/how-clear-all-memory-cache.html
相關推薦
- 2022-09-16 詳解SQL報錯盲注_MsSql
- 2022-04-09 一起來學習一下python的數據類型_python
- 2022-04-12 Windows11右鍵菜單恢復Windows10樣式
- 2023-02-10 C++?stack與queue使用方法詳細講解_C 語言
- 2022-03-25 C語言中字符型數據和浮點型數據介紹_C 語言
- 2022-06-04 Python?pyecharts繪制折線圖詳解_python
- 2022-10-19 C#實現自動生成電子印章_C#教程
- 2022-07-12 Docker-swarm快速搭建redis集群的方法步驟_docker
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支