您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“C#中Helper類如何使用”,內容詳細,步驟清晰,細節處理妥當,希望這篇“C#中Helper類如何使用”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
項目中用戶頻繁訪問數據庫會導致程序的卡頓,甚至堵塞。使用緩存可以有效的降低用戶訪問數據庫的頻次,有效的減少并發的壓力。保護后端真實的服務器。
對于開發人員需要方便調用,所以本文提供了helper類對緩存有了封裝。分了三個Cache,SystemCache,RedisCache(默認緩存,系統緩存,Redis緩存)。話不多說,開擼!
可以看到,csredis支持.net40/.net45/.netstandard平臺,還是比較友好的。
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); } } } }
Redis 是一個開源(BSD許可)的,內存中的數據結構存儲系統,它可以用作數據庫、緩存和消息中間件。
它是基于高性能的Key-Value、并提供多種語言的 API的非關系型數據庫。不過與傳統數據庫不同的是 redis 的數據是存在內存中的,所以存寫速度非常快。
它支持多種類型的數據結構,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets)
讀到這里,這篇“C#中Helper類如何使用”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。