溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#中Helper類如何使用

發(fā)布時(shí)間:2022-04-22 10:10:16 來(lái)源:億速云 閱讀:354 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“C#中Helper類如何使用”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“C#中Helper類如何使用”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。

    使用背景

    項(xiàng)目中用戶頻繁訪問(wèn)數(shù)據(jù)庫(kù)會(huì)導(dǎo)致程序的卡頓,甚至堵塞。使用緩存可以有效的降低用戶訪問(wèn)數(shù)據(jù)庫(kù)的頻次,有效的減少并發(fā)的壓力。保護(hù)后端真實(shí)的服務(wù)器。

    對(duì)于開發(fā)人員需要方便調(diào)用,所以本文提供了helper類對(duì)緩存有了封裝。分了三個(gè)Cache,SystemCache,RedisCache(默認(rèn)緩存,系統(tǒng)緩存,Redis緩存)。話不多說(shuō),開擼!

    使用方法

    1.引用CSRedisCore

    C#中Helper類如何使用

    可以看到,csredis支持.net40/.net45/.netstandard平臺(tái),還是比較友好的。

    2.增加helper類代碼

    CacheHelper.cs

    /// <summary>
        /// 緩存幫助類
        /// </summary>
        public class CacheHelper
        {
            /// <summary>
            /// 靜態(tài)構(gòu)造函數(shù),初始化緩存類型
            /// </summary>
            static CacheHelper()
            {
                SystemCache = new SystemCache();
    
           if(true)       //項(xiàng)目全局變量類,可自行定義
               // 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("請(qǐng)指定緩存類型!");
                }
            }
    
            /// <summary>
            /// 默認(rèn)緩存
            /// </summary>
            public static ICache Cache { get; }
    
            /// <summary>
            /// 系統(tǒng)緩存
            /// </summary>
            public static ICache SystemCache { get; }
    
            /// <summary>
            /// Redis緩存
            /// </summary>
            public static ICache RedisCache { get; }
        }

    ICache.cs

    /// <summary>
        /// 緩存操作接口類
        /// </summary>
        public interface ICache
        {
            #region 設(shè)置緩存
    
            /// <summary>
            /// 設(shè)置緩存
            /// </summary>
            /// <param name="key">主鍵</param>
            /// <param name="value">值</param>
            void SetCache(string key, object value);
    
            /// <summary>
            /// 設(shè)置緩存
            /// 注:默認(rèn)過(guò)期類型為絕對(duì)過(guò)期
            /// </summary>
            /// <param name="key">主鍵</param>
            /// <param name="value">值</param>
            /// <param name="timeout">過(guò)期時(shí)間間隔</param>
            void SetCache(string key, object value, TimeSpan timeout);
    
            /// <summary>
            /// 設(shè)置緩存
            /// 注:默認(rèn)過(guò)期類型為絕對(duì)過(guò)期
            /// </summary>
            /// <param name="key">主鍵</param>
            /// <param name="value">值</param>
            /// <param name="timeout">過(guò)期時(shí)間間隔</param>
            /// <param name="expireType">過(guò)期類型</param>
            void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType);
    
            /// <summary>
            /// 設(shè)置鍵失效時(shí)間
            /// </summary>
            /// <param name="key">鍵值</param>
            /// <param name="expire">從現(xiàn)在起時(shí)間間隔</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">數(shù)據(jù)類型</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>
        /// 過(guò)期類型
        /// </summary>
        public enum ExpireType
        {
            /// <summary>
            /// 絕對(duì)過(guò)期
            /// 注:即自創(chuàng)建一段時(shí)間后就過(guò)期
            /// </summary>
            Absolute,
    
            /// <summary>
            /// 相對(duì)過(guò)期
            /// 注:即該鍵未被訪問(wèn)后一段時(shí)間后過(guò)期,若此鍵一直被訪問(wèn)則過(guò)期時(shí)間自動(dòng)延長(zhǎng)
            /// </summary>
            Relative,
        }
    
        #endregion

    RedisCache.cs

    /// <summary>
        /// Redis緩存
        /// </summary>
        public class RedisCache : ICache
        {
            /// <summary>
            /// 構(gòu)造函數(shù)
            /// 注意:請(qǐng)以單例使用
            /// </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>
        /// 系統(tǒng)緩存幫助類
        /// </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.使用

    C#中Helper類如何使用

    4.說(shuō)明

    Redis 是一個(gè)開源(BSD許可)的,內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲(chǔ)系統(tǒng),它可以用作數(shù)據(jù)庫(kù)、緩存和消息中間件?! ?/p>

    它是基于高性能的Key-Value、并提供多種語(yǔ)言的 API的非關(guān)系型數(shù)據(jù)庫(kù)。不過(guò)與傳統(tǒng)數(shù)據(jù)庫(kù)不同的是 redis 的數(shù)據(jù)是存在內(nèi)存中的,所以存寫速度非??臁?/p>

    它支持多種類型的數(shù)據(jù)結(jié)構(gòu),如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets)

    讀到這里,這篇“C#中Helper類如何使用”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問(wèn)一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI