1:OutputCacheProvider
OutputCacheProvider是一个抽象基类,我们需要override其中的四个方法,它们分别是:
Add 方法,将指定项插入输出缓存中。
Get 方法,返回对输出缓存中指定项的引用。
Remove 方法,从输出缓存中移除指定项。
Set 方法,将指定项插入输出缓存中,如果该项已缓存,则覆盖该项。
2:创建自己的文件缓存处理类
该类型为FileCacheProvider,代码如下:
代码如下:
public class FileCacheProvider : OutputCacheProvider
{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public override void Initialize(string name, NameValueCollection attributes)
{
base.Initialize(name, attributes);
CachePath = HttpContext.Current.Server.MapPath(attributes["cachePath"]);
}
public override object Add(string key, object entry, DateTime utcExpiry)
{
Object obj = Get(key);
if (obj != null) //这一步很重要
{
return obj;
}
Set(key,entry,utcExpiry);
return entry;
}
public override object Get(string key)
{
string path = ConvertKeyToPath(key);
if (!File.Exists(path))
{
return null;
}
CacheItem item = null;
using (FileStream file = File.OpenRead(path))
{
var formatter = new BinaryFormatter();
item = (CacheItem)formatter.Deserialize(file);
}
if (item.ExpiryDate <= DateTime.Now.ToUniversalTime())
{
log.Info(item.ExpiryDate + "*" + key);
Remove(key);
return null;
}
return item.Item;
}
public override void Set(string key, object entry, DateTime utcExpiry)
{
CacheItem item = new CacheItem(entry, utcExpiry);
string path = ConvertKeyToPath(key);
using (FileStream file = File.OpenWrite(path))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(file, item);
}
}
public override void Remove(string key)
{
string path = ConvertKeyToPath(key);
if (File.Exists(path))
File.Delete(path);
}
public string CachePath
{
get;
set;
}
private string ConvertKeyToPath(string key)
{
string file = key.Replace('/', '-');
file += ".txt";
return Path.Combine(CachePath, file);
}
}
[Serializable]
public class CacheItem
{
public DateTime ExpiryDate;
public object Item;
public CacheItem(object entry, DateTime utcExpiry)
{
Item = entry;
新闻热点
疑难解答
图片精选