詳解C#中Helper類的使用
使用背景
項目中用戶頻繁訪問數(shù)據(jù)庫會導致程序的卡頓,甚至堵塞。使用緩存可以有效的降低用戶訪問數(shù)據(jù)庫的頻次,有效的減少并發(fā)的壓力。保護后端真實的服務(wù)器。
對于開發(fā)人員需要方便調(diào)用,所以本文提供了helper類對緩存有了封裝。分了三個Cache,SystemCache,RedisCache(默認緩存,系統(tǒng)緩存,Redis緩存)。話不多說,開擼!
使用方法
1.引用CSRedisCore

可以看到,csredis支持.net40/.net45/.netstandard平臺,還是比較友好的。
2.增加helper類代碼
CacheHelper.cs
/// <summary>
/// 緩存幫助類
/// </summary>
public class CacheHelper
{
/// <summary>
/// 靜態(tài)構(gòu)造函數(shù),初始化緩存類型
/// </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>
/// 系統(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è)置緩存
/// 注:默認過期類型為絕對過期
/// </summary>
/// <param name="key">主鍵</param>
/// <param name="value">值</param>
/// <param name="timeout">過期時間間隔</param>
void SetCache(string key, object value, TimeSpan timeout);
/// <summary>
/// 設(shè)置緩存
/// 注:默認過期類型為絕對過期
/// </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>
/// 設(shè)置鍵失效時間
/// </summary>
/// <param name="key">鍵值</param>
/// <param name="expire">從現(xiàn)在起時間間隔</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>
/// 過期類型
/// </summary>
public enum ExpireType
{
/// <summary>
/// 絕對過期
/// 注:即自創(chuàng)建一段時間后就過期
/// </summary>
Absolute,
/// <summary>
/// 相對過期
/// 注:即該鍵未被訪問后一段時間后過期,若此鍵一直被訪問則過期時間自動延長
/// </summary>
Relative,
}
#endregionRedisCache.cs
/// <summary>
/// Redis緩存
/// </summary>
public class RedisCache : ICache
{
/// <summary>
/// 構(gòu)造函數(shù)
/// 注意:請以單例使用
/// </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.使用

4.說明
Redis 是一個開源(BSD許可)的,內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲系統(tǒng),它可以用作數(shù)據(jù)庫、緩存和消息中間件?! ?/p>
它是基于高性能的Key-Value、并提供多種語言的 API的非關(guān)系型數(shù)據(jù)庫。不過與傳統(tǒng)數(shù)據(jù)庫不同的是 redis 的數(shù)據(jù)是存在內(nèi)存中的,所以存寫速度非??臁?/p>
它支持多種類型的數(shù)據(jù)結(jié)構(gòu),如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets)
結(jié)語
這里提供了helper類,主要是為了封裝緩存,使用起來更加方便。具體可以在其基礎(chǔ)上進行擴展。
到此這篇關(guān)于詳解C#中Helper類的使用的文章就介紹到這了,更多相關(guān)C# Helper類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# ComboBox控件“設(shè)置 DataSource 屬性后無法修改項集合”的完美解決方法
這篇文章主要介紹了C# ComboBox控件“設(shè)置 DataSource 屬性后無法修改項集合”的解決方法,非常不錯具有一定的參考借鑒價值,需要的朋友可以參考下2016-11-11

