c# Redis緩存的使用和helper類;


使用背景:

      項目中用戶頻繁訪問數據庫會導致程序的卡頓,甚至堵塞。使用緩存可以有效的降低用戶訪問數據庫的頻次,有效的減少並發的壓力。保護后端真實的服務器。

    對於開發人員需要方便調用,所以本文提供了helper類對緩存有了封裝。分了三個Cache,SystemCache,RedisCache(默認緩存,系統緩存,Redis緩存)。話不多說,開擼!

使用方法:

      1,引用CSRedisCore

      

 

      可以看到,csredis支持.net40/.net45/.netstandard平台,還是比較友好的。

      2,增加helper類代碼

      

CacheHelper.cs

    /// <summary>
    /// 緩存幫助類
    /// </summary>
    public class CacheHelper
    {
        /// <summary>
        /// 靜態構造函數,初始化緩存類型
        /// </summary>
        static CacheHelper()
        {
            SystemCache = new SystemCache();

       if(true)
       //項目全局變量類,可自行定義
 // if (GlobalSwitch.OpenRedisCache) { try { RedisCache = new RedisCache(GlobalSwitch.RedisConfig); } catch { } } switch (GlobalSwitch.CacheType) { case CacheType.SystemCache:Cache = SystemCache;break; case CacheType.RedisCache:Cache = RedisCache;break; default:throw new Exception("請指定緩存類型!"); } } /// <summary>
        /// 默認緩存 /// </summary>
        public static ICache Cache { get; } /// <summary>
        /// 系統緩存 /// </summary>
        public static ICache SystemCache { get; } /// <summary>
        /// Redis緩存 /// </summary>
        public static ICache RedisCache { get; } }

ICache.cs:

    /// <summary>
    /// 緩存操作接口類
    /// </summary>
    public interface ICache
    {
        #region 設置緩存

        /// <summary>
        /// 設置緩存
        /// </summary>
        /// <param name="key">主鍵</param>
        /// <param name="value"></param>
        void SetCache(string key, object value);

        /// <summary>
        /// 設置緩存
        /// 注:默認過期類型為絕對過期
        /// </summary>
        /// <param name="key">主鍵</param>
        /// <param name="value"></param>
        /// <param name="timeout">過期時間間隔</param>
        void SetCache(string key, object value, TimeSpan timeout);

        /// <summary>
        /// 設置緩存
        /// 注:默認過期類型為絕對過期
        /// </summary>
        /// <param name="key">主鍵</param>
        /// <param name="value"></param>
        /// <param name="timeout">過期時間間隔</param>
        /// <param name="expireType">過期類型</param>
        void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType);

        /// <summary>
        /// 設置鍵失效時間
        /// </summary>
        /// <param name="key">鍵值</param>
        /// <param name="expire">從現在起時間間隔</param>
        void SetKeyExpire(string key, TimeSpan expire);

        #endregion

        #region 獲取緩存

        /// <summary>
        /// 獲取緩存
        /// </summary>
        /// <param name="key">主鍵</param>
        object GetCache(string key);

        /// <summary>
        /// 獲取緩存
        /// </summary>
        /// <param name="key">主鍵</param>
        /// <typeparam name="T">數據類型</typeparam>
        T GetCache<T>(string key) where T : class;

        /// <summary>
        /// 是否存在鍵值
        /// </summary>
        /// <param name="key">主鍵</param>
        /// <returns></returns>
        bool ContainsKey(string key);

        #endregion

        #region 刪除緩存

        /// <summary>
        /// 清除緩存
        /// </summary>
        /// <param name="key">主鍵</param>
        void RemoveCache(string key);

        #endregion
    }

    #region 類型定義

    /// <summary>
    /// 值信息
    /// </summary>
    public struct ValueInfoEntry
    {
        public string Value { get; set; }
        public string TypeName { get; set; }
        public TimeSpan? ExpireTime { get; set; }
        public ExpireType? ExpireType { get; set; }
    }

    /// <summary>
    /// 過期類型
    /// </summary>
    public enum ExpireType
    {
        /// <summary>
        /// 絕對過期
        /// 注:即自創建一段時間后就過期
        /// </summary>
        Absolute,

        /// <summary>
        /// 相對過期
        /// 注:即該鍵未被訪問后一段時間后過期,若此鍵一直被訪問則過期時間自動延長
        /// </summary>
        Relative,
    }

    #endregion

RedisCache.cs

 /// <summary>
    /// Redis緩存
    /// </summary>
    public class RedisCache : ICache
    {
        /// <summary>
        /// 構造函數
        /// 注意:請以單例使用
        /// </summary>
        /// <param name="config">配置字符串</param>
        public RedisCache(string config)
        {
            _redisCLient = new CSRedisClient(config);
        }
        private CSRedisClient _redisCLient { get; }

        public bool ContainsKey(string key)
        {
            return _redisCLient.Exists(key);
        }

        public object GetCache(string key)
        {
            object value = null;
            var redisValue = _redisCLient.Get(key);
            if (redisValue.IsNullOrEmpty())
                return null;
            ValueInfoEntry valueEntry = redisValue.ToString().ToObject<ValueInfoEntry>();
            if (valueEntry.TypeName == typeof(string).AssemblyQualifiedName)
                value = valueEntry.Value;
            else
                value = valueEntry.Value.ToObject(Type.GetType(valueEntry.TypeName));

            if (valueEntry.ExpireTime != null && valueEntry.ExpireType == ExpireType.Relative)
                SetKeyExpire(key, valueEntry.ExpireTime.Value);

            return value;
        }

        public T GetCache<T>(string key) where T : class
        {
            return (T)GetCache(key);
        }

        public void SetKeyExpire(string key, TimeSpan expire)
        {
            _redisCLient.Expire(key, expire);
        }

        public void RemoveCache(string key)
        {
            _redisCLient.Del(key);
        }

        public void SetCache(string key, object value)
        {
            _SetCache(key, value, null, null);
        }

        public void SetCache(string key, object value, TimeSpan timeout)
        {
            _SetCache(key, value, timeout, ExpireType.Absolute);
        }

        public void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType)
        {
            _SetCache(key, value, timeout, expireType);
        }

        private void _SetCache(string key, object value, TimeSpan? timeout, ExpireType? expireType)
        {
            string jsonStr = string.Empty;
            if (value is string)
                jsonStr = value as string;
            else
                jsonStr = value.ToJson();

            ValueInfoEntry entry = new ValueInfoEntry
            {
                Value = jsonStr,
                TypeName = value.GetType().AssemblyQualifiedName,
                ExpireTime = timeout,
                ExpireType = expireType
            };

            string theValue = entry.ToJson();
            if (timeout == null)
                _redisCLient.Set(key, theValue);
            else
                _redisCLient.Set(key, theValue, (int)timeout.Value.TotalSeconds);
        }
    }

SystemCache.cs

    /// <summary>
    /// 系統緩存幫助類
    /// </summary>
    public class SystemCache : ICache
    {
        public object GetCache(string key)
        {
            return HttpRuntime.Cache[key];
        }

        public T GetCache<T>(string key) where T : class
        {
            return (T)HttpRuntime.Cache[key];
        }

        public bool ContainsKey(string key)
        {
            return GetCache(key) != null;
        }

        public void RemoveCache(string key)
        {
            HttpRuntime.Cache.Remove(key);
        }

        public void SetKeyExpire(string key, TimeSpan expire)
        {
            object value = GetCache(key);
            SetCache(key, value, expire);
        }

        public void SetCache(string key, object value)
        {
            _SetCache(key, value, null, null);
        }

        public void SetCache(string key, object value, TimeSpan timeout)
        {
            _SetCache(key, value, timeout, ExpireType.Absolute);
        }

        public void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType)
        {
            _SetCache(key, value, timeout, expireType);
        }

        private void _SetCache(string key, object value, TimeSpan? timeout, ExpireType? expireType)
        {
            if (timeout == null)
                HttpRuntime.Cache[key] = value;
            else
            {
                if (expireType == ExpireType.Absolute)
                {
                    DateTime endTime = DateTime.Now.AddTicks(timeout.Value.Ticks);
                    HttpRuntime.Cache.Insert(key, value, null, endTime, Cache.NoSlidingExpiration);
                }
                else
                {
                    HttpRuntime.Cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, timeout.Value);
                }
            }
        }
    }

 

       3,使用

      

 

 

 

      4,說明: 

      Redis 是一個開源(BSD許可)的,內存中的數據結構存儲系統,它可以用作數據庫、緩存和消息中間件。  
      它是基於高性能的Key-Value、並提供多種語言的 API的非關系型數據庫。不過與傳統數據庫不同的是 redis 的數據是存在內存中的,所以存寫速度非常快。
      它支持多種類型的數據結構,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets)

結語:

    這里提供了helper類,主要是為了封裝緩存,使用起來更加方便。具體可以在其基礎上進行擴展。

      


免責聲明!

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



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