国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

ASP.NET性能優化之構建自定義文件緩存

2024-07-10 12:41:48
字體:
來源:轉載
供稿:網友
現在,借助于.NET4.0中的OutputCacheProvider,我們可以有多種選擇創建自己的緩存。如,我們可以把HTML輸出緩存存儲到memcached分布式集群服務器,或者MongoDB中(一種常用的面向文檔數據庫,不妨閱讀本篇http://msdn.microsoft.com/zh-cn/magazine/gg650661.aspx)。當然,我們也可以把緩存作為文件存儲到硬盤上,考慮到可擴展性,這是一種最廉價的做法,本文就是介紹如果構建自定義文件緩存。

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;

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 启东市| 鄂伦春自治旗| 高台县| 云南省| 隆尧县| 靖边县| 固安县| 琼中| 晋州市| 青冈县| 麻城市| 拉孜县| 奇台县| 石嘴山市| 阿拉善左旗| 郓城县| 陆丰市| 土默特右旗| 河西区| 南郑县| 六枝特区| 福鼎市| 古交市| 云南省| 内丘县| 昌图县| 门源| 万载县| 琼海市| 灵寿县| 时尚| 定州市| 河间市| 麟游县| 高碑店市| 白河县| 集贤县| 泊头市| 都昌县| 怀集县| 曲周县|