using Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
namespace KC.Cache.WebCache
{
public class WebCache:ICache
{
protected static volatile System.Web.Caching.Cache webCache = HttpRuntime.Cache;
private static int timeOut = ConfigHelper.GetValue("OutTime").TryToInt32();
///
/// 写入缓存,单体
///
/// 对象数据
/// 键
/// 几秒过期
public void WriteCache(string cacheKey, T value, int seconds = 0) where T : class
{
if (String.IsNullOrEmpty(cacheKey) || value == null)
return;
if (seconds == 0)
seconds = timeOut;
var callBack = new CacheItemRemovedCallback(onRemove);
webCache.Insert(cacheKey, value, null, System.DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, callBack);
}
///
/// 读取缓存,单体
///
/// 键
///
public T GetCache(string cacheKey) where T : class
{
if (!String.IsNullOrEmpty(cacheKey))
return (T)webCache.Get(cacheKey);
return default(T);
}
///
/// 获取所有key
///
///
public List GetAllKeys()
{
List list = new List();
var enu = webCache.GetEnumerator();
while (enu.MoveNext())
{
list.Add(enu.Key.ToString());
}
return list;
}
///
/// 确定当前Key是否过期
///
///
///
public bool HasExpire(string cacheKey)
{
if (string.IsNullOrEmpty(cacheKey))
return false;
return webCache[cacheKey] != null;
}
///
/// 移除指定数据缓存
///
/// 键
public void RemoveCache(string cacheKey)
{
if (!String.IsNullOrEmpty(cacheKey))
webCache.Remove(cacheKey);
}
///
/// 批量删除数据缓存
///
///
public void RemoveCache(List keys)
{
if (keys.Count > 0)
{
var enu = webCache.GetEnumerator();
while (enu.MoveNext())
{
string key = enu.Key.ToString();
if (keys.Where(p => p == key).Count() > 0)
{
RemoveCache(key);
}
}
}
}
#region MyRegion
public void onRemove(string key, object val, CacheItemRemovedReason reason)
{
switch (reason)
{
case CacheItemRemovedReason.DependencyChanged:
//更新缓存映射表
break;
case CacheItemRemovedReason.Expired:
//更新缓存映射表
break;
case CacheItemRemovedReason.Removed:
break;
case CacheItemRemovedReason.Underused:
break;
default:
break;
}
}
#endregion
}
}