本文实例讲述了C#中Memcached缓存的用法,分享给大家供大家参考。具体方法如下:
ICacheStrategy.cs文件如下:
///
/// 添加数据到缓存 (依赖其它缓存)
///
/// 缓存名称
/// 缓存内容
/// 缓存时间(秒)
/// 依赖缓存名称数组
void AddCacheDepend(string objId, object o, int second, string[] dependKey);
///
/// 添加数据到缓存 (依赖文件)
///
/// 缓存名称
/// 缓存内容
/// 缓存时间(秒)
/// 依赖缓存名称文件名数组
void AddFileDepend(string objId, object o, int second, string[] files);
///
/// 删除指定缓存
///
///
void RemoveCache(string objId);
///
/// 删除所有缓存
///
void RemoveCacheAll();
///
/// 删除匹配到的缓存
///
///
///
void RemoveCacheRegex(string pattern);
///
/// 获取所有缓存键
///
///
IList
///
/// 搜索 匹配到的缓存
///
///
///
IList
///
/// 获得缓存数据
///
///
///
object GetCacheData(string objId);
///
/// 判断此缓存是否有效
///
///
///
bool HasCache(string objID);
}
MemcachedStrategy.cs文件如下:
///
/// 添加数据到缓存
///
/// 缓存名称
/// 缓存内容
/// 缓存时间(秒)
public void Add(string objId, object o, int second)
{
if (second > 0)
{
MemcachedManager.CacheClient.Set(objId, o, DateTime.Now.AddSeconds(second));
}
else
{
MemcachedManager.CacheClient.Set(objId, o);
}
}
#region 缓存依赖没有用到memcached
///
/// 添加数据到缓存 (依赖其它缓存)
///
/// 缓存名称
/// 缓存内容
/// 缓存时间(秒)
/// 依赖缓存名称数组
public void AddCacheDepend(string objId, object o, int second, string[] dependKey)
{
CacheDependency dependencies = new CacheDependency(null, dependKey, DateTime.Now);
HttpRuntime.Cache.Insert(objId, o, dependencies, DateTime.Now.AddSeconds((double)second), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}
///
/// 添加数据到缓存 (依赖文件)
///
/// 缓存名称
/// 缓存内容
/// 缓存时间(秒)
/// 依赖缓存名称文件名数组
public void AddFileDepend(string objId, object o, int second, string[] files)
{
CacheDependency dependencies = new CacheDependency(files, DateTime.Now);
HttpRuntime.Cache.Insert(objId, o, dependencies, DateTime.Now.AddSeconds((double)second), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}
#endregion
///
/// 删除指定缓存
///
///
public void RemoveCache(string objId)
{
if (MemcachedManager.CacheClient.KeyExists(objId))
MemcachedManager.CacheClient.Delete(objId);
}
///
/// 删除所有缓存
///
public void RemoveCacheAll()
{
MemcachedManager.CacheClient.FlushAll();
}
///
/// 删除匹配到的缓存
///
///
public void RemoveCacheRegex(string pattern)
{
IList
foreach (var item in list)
{
MemcachedManager.CacheClient.Delete(item);
}
}
///
/// 获取所有缓存键
///
///
public IList
{
return MemcachedManager.GetAllKeys();
}
///
/// 搜索 匹配到的缓存
///
///
///
public IList
{
List
IList
foreach (var item in cacheKeys)
{
if (Regex.IsMatch(item, pattern))
{
l.Add(item);
}
}
return l.AsReadOnly();
}
///
/// 获得缓存数据
///
///
///
public object GetCacheData(string objId)
{
return MemcachedManager.CacheClient.Get(objId);
}
///
/// 判断此缓存是否有效
///
///
///
public bool HasCache(string objID)
{
return MemcachedManager.CacheClient.KeyExists(objID);
}
#endregion
}
希望本文所述对大家的C#程序设计有所帮助。