溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

ASP.NET中怎么構(gòu)建自定義文件緩存

發(fā)布時(shí)間:2021-12-06 15:25:38 來(lái)源:億速云 閱讀:173 作者:iii 欄目:編程語(yǔ)言

本篇內(nèi)容介紹了“ASP.NET中怎么構(gòu)建自定義文件緩存”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

ASP.NET的輸出緩存(即靜態(tài)HTML)在.NET4.0前一直是基于內(nèi)存的。這意味著如果我們的站點(diǎn)含有大量的緩存,則很容易消耗掉本機(jī)內(nèi)存?,F(xiàn)在,借助于.NET4.0中的OutputCacheProvider,我們可以有多種選擇創(chuàng)建自己的緩存。如,我們可以把HTML輸出緩存存儲(chǔ)到memcached分布式集群服務(wù)器,或者MongoDB中。當(dāng)然,我們也可以把緩存作為文件存儲(chǔ)到硬盤(pán)上,考慮到可擴(kuò)展性,這是一種最廉價(jià)的做法。

1:OutputCacheProvider

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

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

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

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

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

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

該類(lèi)型為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;  }  }

有兩個(gè)地方需要特別說(shuō)明:

在Add方法中,有一個(gè)條件判斷,必須做出這樣的處理,否則緩存機(jī)制將會(huì)緩存***次的結(jié)果,過(guò)了有效期后緩存講失效并不再重建;

在示例程序中,我們簡(jiǎn)單的將緩存放到了Cache目錄下,在實(shí)際的項(xiàng)目實(shí)踐中,考慮到緩存的頁(yè)面將是成千上萬(wàn)的,所以我們必須要做目錄分級(jí),否則尋找并讀取緩存文件將會(huì)成為效率瓶頸,這會(huì)耗盡CPU。

3:配置文件

我們需要在Web.config中配置緩存處理程序是自定義的FileCacheProvider,即在 <system.web>下添加節(jié)點(diǎn):

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

4:緩存的使用

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

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

現(xiàn)在,我們開(kāi)始評(píng)價(jià)下有輸出緩存和無(wú)輸出緩存的性能對(duì)比,模擬100個(gè)用戶(hù)并發(fā)1000次請(qǐng)求如下:

ASP.NET中怎么構(gòu)建自定義文件緩存

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

6:代碼下載

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

“ASP.NET中怎么構(gòu)建自定義文件緩存”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI