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公共類

 

         

public  class 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 static  void 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>
        public  static 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 static  T 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 static  void 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);

 

 

 


 

  歡迎大家掃描下方二維碼,和我一起學習更多的知識😊

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM