ASP.NET性能優(yōu)化之構(gòu)建自定義文件緩存
1:OutputCacheProvider
OutputCacheProvider是一個抽象基類,我們需要override其中的四個方法,它們分別是:
Add 方法,將指定項插入輸出緩存中。
Get 方法,返回對輸出緩存中指定項的引用。
Remove 方法,從輸出緩存中移除指定項。
Set 方法,將指定項插入輸出緩存中,如果該項已緩存,則覆蓋該項。
2:創(chuàng)建自己的文件緩存處理類
該類型為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;
ExpiryDate = utcExpiry;
}
}
有兩個地方需要特別說明:
在Add方法中,有一個條件判斷,必須做出這樣的處理,否則緩存機(jī)制將會緩存第一次的結(jié)果,過了有效期后緩存講失效并不再重建;
在示例程序中,我們簡單的將緩存放到了Cache目錄下,在實際的項目實踐中,考慮到緩存的頁面將是成千上萬的,所以我們必須要做目錄分級,否則尋找并讀取緩存文件將會成為效率瓶頸,這會耗盡CPU。
3:配置文件
我們需要在Web.config中配置緩存處理程序是自定義的FileCacheProvider,即在 <system.web>下添加節(jié)點:
<caching>
<outputCache defaultProvider="FileCache">
<providers>
<add name="FileCache" 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秒。
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次請求如下:
可以看到,有輸出緩存后,吞吐率明顯提高了10倍。
6:代碼下載
FileCacheProvider的原始代碼來自于網(wǎng)絡(luò),我修改了其中的BUG,全部代碼下載如下:MvcApplication20110907.rar
- ASP.NET性能優(yōu)化之局部緩存分析
- ASP.NET 性能優(yōu)化之反向代理緩存使用介紹
- ASP.NET性能優(yōu)化之讓瀏覽器緩存動態(tài)網(wǎng)頁的方法
- ASP.NET性能優(yōu)化小結(jié)(ASP.NET&C#)
- asp.net 程序性能優(yōu)化的七個方面 (c#(或vb.net)程序改進(jìn))
- ASP.NET比較常用的26個性能優(yōu)化技巧
- asp.net小談網(wǎng)站性能優(yōu)化
- ASP.NET性能優(yōu)化之減少請求
- ASP.NET技巧:同時對多個文件進(jìn)行大量寫操作對性能優(yōu)化
- asp.net性能優(yōu)化之使用Redis緩存(入門)
相關(guān)文章
asp.net core常見的4種數(shù)據(jù)加密算法
這篇文章主要介紹了asp.net core常見的4種數(shù)據(jù)加密算法,文中代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06asp.net 編譯器錯誤信息: CS0006: 未能找到元數(shù)據(jù)文件 該死的.NET
今天公司新上一臺志強(qiáng)虛擬主機(jī) 所有配置都好了 給客戶調(diào)整.net 出現(xiàn)了報錯2009-06-06保護(hù).net中的dll文件方法(防止破解、反編譯dll)
.net是一種建立在虛擬機(jī)上執(zhí)行的語言,它直接生成 MSIL 的中間語言,再由.net編譯器 JIT 解釋映象為本機(jī)代碼并交付CPU執(zhí)行。中間語言很容易被反編譯,所以研究下如何有效的保護(hù)dll文件2013-02-02.Net Core微信服務(wù)商二次進(jìn)件的開發(fā)
這篇文章主要介紹了.Net Core微信服務(wù)商二次進(jìn)件的開發(fā),包括服務(wù)商證書獲取方法及查詢進(jìn)件狀態(tài)的詳細(xì)代碼,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-10-10asp.net 枚舉文件里面的數(shù)字綁定到DropDownList里面去
將枚舉文件里面的數(shù)字綁定到DropDownList里面去的實現(xiàn)方法,大家可以借鑒下。2009-07-07Razor TagHelper實現(xiàn)Markdown轉(zhuǎn)HTML的方法
下面小編就為大家分享一篇Razor TagHelper實現(xiàn)Markdown轉(zhuǎn)HTML的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12