首頁 > 軟體

詳解C#中Helper類的使用

2022-04-22 10:00:06

使用背景

專案中使用者頻繁存取資料庫會導致程式的卡頓,甚至堵塞。使用快取可以有效的降低使用者存取資料庫的頻次,有效的減少並行的壓力。保護後端真實的伺服器。

對於開發人員需要方便呼叫,所以本文提供了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類,主要是為了封裝快取,使用起來更加方便。具體可以在其基礎上進行擴充套件。

到此這篇關於詳解C#中Helper類的使用的文章就介紹到這了,更多相關C# Helper類內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com