Redis--Memched--Cache快取介紹使用
目錄:
一、分散式快取—Redis與Memched的區別
1.1、 資料支援型別
1.2、 永續性
1.3、 記憶體利用情況
1.4、 資料一致性
1.5、 效能區別
1.6、 總結
二、記憶體快取—Cache(.Net Core)
2.1、 介紹適用場景
2.2、 提供的過期的方式
2.3、 如何使用
一、分散式快取—Redis與Memched的區別
1.1、 資料支援型別
Redis:支援String(字串)、Hash(雜湊)、List(列表)、Set(集合)、 ZSet(有序集合)、Bitmaps(點陣圖)、HyperLogLog、Geo(地理資訊定位)
Memched:簡單的key/value資料型別
1.2、 永續性
Redis:Redis通過 RDB與AOF持久化,可以將記憶體中的資料儲存到硬碟中,然後重啟之後在讀取資料
Memched:不支援資料的永續性的儲存
1.3、 記憶體利用情況
使用簡單的key-value儲存的話,Memcached的記憶體利用率更高,而如果Redis採用hash結構來做key-value儲存,由於其組合式的壓縮,其記憶體利用率會高於Memcached。
Memcached預設使用Slab Allocation機制管理記憶體,主要思想是按照原先預定的大小分配記憶體大小,當客戶端發過來資料的時候會選擇一個最適合的地方給它儲存,,好處是效率高,
不會造成記憶體碎片,但是不好的一點就是分配的記憶體大小124位元組,傳進來的大小是100位元組,那麼24位元組的記憶體也就浪費了。
1.4、 資料一致性
Redis:單執行緒保證了資料的順序,同時redis還有事務操作
Memcached:memcache需要使用cas保證資料一致性。CAS(Check and Set)是一個確保併發一致性的機制,屬於“樂觀鎖”範疇;原理很簡單:拿版本號,操作,對比版本號,
如果一致就操作,不一致就放棄任何操作
1.5、 效能區別
Redis使用單核,Memcached可以使用多核,所以在處理小的檔案的時候Redis會比Memcached有更高的效率,但是在100KB以上的時候,Memcached的效率就會比Redis更高一點
1.6、 總結
以上就是Redis和Memcached大致的比較了。各有各的優點以及缺點,存在即合理,只有在使用在合適的運用場景,才是最有效率的。
二、記憶體快取—Cache(.Net Core)
2.1、介紹適用場景
Cache,中譯名高速緩衝儲存器,其作用是為了更好的利用區域性性原理,減少CPU訪問主存的次數。簡單地說,CPU正在訪問的指令和資料,其可能會被以後多次訪問到,或者是該指令和資料附近的記憶體區域,也可能會被多次訪問。因此,第一次訪問這一塊區域時,將其複製到Cache中,以後訪問該區域的指令或者資料時,就不用再從主存中取出。
記憶體快取可以儲存任何物件; 分散式快取介面僅限於byte[]
。記憶體和分散式快取將快取項儲存為鍵值對。
2.2、提供的過期的方式
主要介紹兩種:
- 絕對到期(指定在一個固定的時間點到期)
- 滑動到期(在一個時間長度內沒有被命中則過期)
2.3、如何使用
新建一個CacheHelper 公共類
publicclass CacheHelper { private static IMemoryCache _memoryCache; public CacheHelper(IMemoryCache memoryCache) { _memoryCache = memoryCache; } /// <summary> /// 建立絕對過期時間快取 /// </summary> /// <param name="cacheKey">快取key</param> /// <param name="obj">快取物件</param> /// <param name="expireDate">過期時間(絕對)分鐘</param> public staticvoid SetAbsolute(string cacheKey, object obj,int expireDate= 10 * 60) { //絕對到期時間 var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(expireDate)); _memoryCache.Set(cacheKey, obj, cacheEntryOptions); } /// <summary> /// 每隔多長時間不呼叫就讓其過期 /// </summary> /// <param name="cacheKey">快取key</param> /// <param name="obj">快取物件</param> /// <param name="expireDate">過期時間(訪問快取重置時間)</param> public static void SetSliding(string cacheKey, object obj, int expireDate= 10 * 60) { //絕對到期時間 var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(expireDate)); _memoryCache.Set(cacheKey, obj, cacheEntryOptions); } /// <summary> /// 判斷快取是否存在 /// </summary> /// <param name="key">快取key</param> /// <returns></returns> publicstatic bool IsExist(string cacheKey) { if (string.IsNullOrWhiteSpace(cacheKey)) { return false; } return _memoryCache.TryGetValue(cacheKey, out _); } /// <summary> /// 獲取快取物件 /// </summary> /// <param name="cacheKey">快取key</param> /// <returns>object物件</returns> public static object Get(string cacheKey) { if (string.IsNullOrEmpty(cacheKey)) { return null; } return_memoryCache.Get(cacheKey); } /// <summary> /// 獲取快取物件 /// </summary> /// <typeparam name="T">T物件</typeparam> /// <param name="cacheKey">快取Key</param> /// <returns></returns> public staticT Get<T>(string cacheKey) { if (string.IsNullOrEmpty(cacheKey)) { return default(T); } if (!_memoryCache.TryGetValue<T>(cacheKey, out T cacheEntry)) { return default(T); } return cacheEntry; } /// <summary> /// 獲取所有快取鍵 /// </summary> /// <returns></returns> public static List<string> GetCacheKeys() { const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; var entries = _memoryCache.GetType().GetField("_entries", flags).GetValue(_memoryCache); var cacheItems = entries as IDictionary; var keys = new List<string>(); if (cacheItems == null) return keys; foreach (DictionaryEntry cacheItem in cacheItems) { keys.Add(cacheItem.Key.ToString()); } return keys; } /// <summary> /// 移除指定資料快取 /// </summary> /// <param name="cacheKey">快取key</param> public staticvoid RemoveCache(string cacheKey) { _memoryCache.Remove(cacheKey); } /// <summary> /// 移除全部快取 /// </summary> public static void RemoveAllCache() { var keysList = GetCacheKeys(); foreach (string key in keysList) { _memoryCache.Remove(key); } } }
然後根據前兩篇文章所講的依賴注入在Startup.cs裡面註冊
services.AddMemoryCache(); services.AddSingleton<CacheHelper>();
然後就可以正常使用了。
CacheHelper.SetAbsolute("admin", admin, 10 * 60);