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

首頁 > 編程 > .NET > 正文

ASP.NET性能優(yōu)化之構(gòu)建自定義文件緩存

2024-07-10 13:24:54
字體:
供稿:網(wǎng)友
現(xiàn)在,借助于.NET4.0中的OutputCacheProvider,我們可以有多種選擇創(chuàng)建自己的緩存。如,我們可以把HTML輸出緩存存儲到memcached分布式集群服務(wù)器,或者M(jìn)ongoDB中(一種常用的面向文檔數(shù)據(jù)庫,不妨閱讀本篇)。當(dāng)然,我們也可以把緩存作為文件存儲到硬盤上,考慮到可擴(kuò)展性,這是一種最廉價的做法,本文就是介紹如果構(gòu)建自定義文件緩存。

1:OutputCacheProvider

OutputCacheProvider是一個抽象基類,我們需要override其中的四個方法,它們分別是:

Add 方法,將指定項(xiàng)插入輸出緩存中。

Get 方法,返回對輸出緩存中指定項(xiàng)的引用。

Remove 方法,從輸出緩存中移除指定項(xiàng)。

Set 方法,將指定項(xiàng)插入輸出緩存中,如果該項(xiàng)已緩存,則覆蓋該項(xiàng)。

2:創(chuàng)建自己的文件緩存處理類

該類型為FileCacheProvider,代碼如下:

復(fù)制代碼 代碼如下:


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('http://m.survivalescaperooms.com/', '-');
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;
ExpiryDate = utcExpiry;
}
}


有兩個地方需要特別說明:
在Add方法中,有一個條件判斷,必須做出這樣的處理,否則緩存機(jī)制將會緩存第一次的結(jié)果,過了有效期后緩存講失效并不再重建;
在示例程序中,我們簡單的將緩存放到了Cache目錄下,在實(shí)際的項(xiàng)目實(shí)踐中,考慮到緩存的頁面將是成千上萬的,所以我們必須要做目錄分級,否則尋找并讀取緩存文件將會成為效率瓶頸,這會耗盡CPU。
3:配置文件
我們需要在Web.config中配置緩存處理程序是自定義的FileCacheProvider,即在 <system.web>下添加節(jié)點(diǎn):

復(fù)制代碼 代碼如下:


<caching>
<outputCache defaultProvider="FileCache">
<providers>
<add type="MvcApplication2.Common.FileCacheProvider" cachePath="~/Cache" />
</providers>
</outputCache>
</caching>


4:緩存的使用
我們假設(shè)在MVC的控制中使用(如果要在ASP.NET頁面中使用,則在頁面中包含<%@OutputCache VaryByParam="none" Duration="10" %>),可以看到,Index是未進(jìn)行輸出緩存的,而Index2進(jìn)行了輸出緩存,緩存時間為10秒。

復(fù)制代碼 代碼如下:


public class HomeController : Controller
{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static string s_conn = "Data Source=192.168.0.77;Initial Catalog=luminjidb;User Id=sa;Password=sa;";
public ActionResult Index()
{
using (DataSet ds = Common.SqlHelper.ExecuteDataset(s_conn, CommandType.Text, "select top 1* from NameTb a, DepTb b where a.DepID = b.ID ORDER BY NEWID()"))
{
ViewBag.Message = ds.Tables[0].Rows[0]["name"].ToString();
}
return View();
}
[OutputCache(Duration = 10, VaryByParam = "none")]
public ActionResult Index2()
{
using (DataSet ds = Common.SqlHelper.ExecuteDataset(s_conn, CommandType.Text, "select top 1* from NameTb a, DepTb b where a.DepID = b.ID ORDER BY NEWID()"))
{
ViewBag.Message = ds.Tables[0].Rows[0]["name"].ToString();
}
return View();
}
}


5:查看下效果

上面的代碼,在訪問了Index2后,將會在Cache文件夾下產(chǎn)生緩存文件,如下:

現(xiàn)在,我們開始評價下有輸出緩存和無輸出緩存的性能對比,模擬100個用戶并發(fā)1000次請求如下:

ASP.NET性能優(yōu)化之構(gòu)建自定義文件緩存

可以看到,有輸出緩存后,吞吐率明顯提高了10倍。

6:代碼下載

FileCacheProvider的原始代碼來自于網(wǎng)絡(luò),我修改了其中的BUG,全部代碼下載如下:MvcApplication20110907.rar

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 青河县| 公主岭市| 炉霍县| 梨树县| 松原市| 抚顺县| 平利县| 綦江县| 虹口区| 若尔盖县| 鱼台县| 明溪县| 来凤县| 福建省| 子长县| 莫力| 西安市| 隆林| 新田县| 井冈山市| 建宁县| 涞水县| 盱眙县| 大埔县| 香河县| 文昌市| 夹江县| 裕民县| 汉中市| 巴塘县| 波密县| 旬邑县| 克拉玛依市| 金湖县| 建平县| 康保县| 康保县| 肇源县| 靖江市| 吉安县| 哈尔滨市|