ASP.NET Cache缓存的使用

       ASP.NET Cache是提高系统性能的重要方法,它使用了“最近使用”原则(a least-recently-used algorithm)。在数据库访问中常常会用到Cache保存数据库数据。html

1.缓存的添加:数据库

Cache的添加方法有Add()Insert(),两种方法几乎相似,只是Inser方法能够使用可选参数,即便用默认参数,来实现缓存的添加:缓存

Cache.Add(less

       KeyName,//缓存名post

       KeyValue,//要缓存的对象性能

       Dependencies,//依赖项ui

       AbsoluteExpiration,//绝对过时时间this

       SlidingExpiration,//相对过时时间spa

       Priority,//优先级orm

       CacheItemRemovedCallback);//缓存过时引起事件

2. 缓存依赖项:

       缓存能够设置的时效性能够经过 文件依赖,其余缓存依赖,数据库依赖和过时时间方法来设置,当文件改变,依赖缓存项改变,数据库改变或时间的到期时,缓存会失效,并能够引起必定事件。

2.1 文件依赖:

        CacheDependency fileDepends = new CacheDependency(Server.MapPath("Northwind.xml"));
        Cache.Insert("GridViewDataSet", dsGrid, fileDepends);
此例为经过Northiwind.xml文件依赖出来缓存的用法:
2.2 其余缓存项依赖:
string[] fileDependsArray = {Server.MapPath("Northwind.xml")};
string[] cacheDependsArray = {"Depend0", "Depend1", "Depend2"};
CacheDependency cacheDepends = new CacheDependency(fileDependsArray, cacheDependsArray);
Cache.Insert("GridViewDataSet", dsGrid, cacheDepends);
此例设置了Northwind.xml文件依赖和 Depend0,depend1,Depend2缓存项
其中Depend0,depend1,Depend2为另外三个缓存。
若是不须要文件依赖能够设置为NULL。 
2.3 过时时间设定:
AbsoluteExpiration能够设置缓存的绝对过时时间,如:
Cache.Insert("GridViewDataSet ", dsGrid, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
缓存会在添加起30分钟后过时。
NoSlidingExpiration能够设置相对过时时间,若是缓存在NoSlidingExpiration设定的时间内没有被访问,缓存过时,若是在这段时间内有访问,则缓存过时时间将会重置为原始值,如NoSlidingExpiration=20
在20分钟内若是没有被访问,缓存过时,若是每次19分钟访问缓存,缓存将永远不会过时。
Cache.Insert("DataGridDataSet", dsGrid, null,Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(30));
3. 优先级:
        Priority属性值和意义:

Priority value

Description

NotRemovable

Items with this priority will not be evicted.

High

Items with this priority level are the least likely to be evicted.

AboveNormal

Items with this priority level are less likely to be evicted than items assigned Normal priority.

Default

This is equivalent to Normal.

Normal

The default value.

BelowNormal

Items with this priority level are more likely to be evicted than items assigned Normal priority.

Low

Items with this priority level are the most likely to be evicted.

 

4. 缓存失效事件处理:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;         // necessary for CacheDependency
using System.Xml;                  // necessary for Xml stuff
 
public partial class _Default : System.Web.UI.Page
{
   public static CacheItemRemovedCallback onRemove = null;
 
   protected void Page_Load(object sender, EventArgs e)
    {
       CreateGridView( );
    }
 
    private void CreateGridView( )
    {
       DataSet dsGrid;
       dsGrid = (DataSet)Cache["GridViewDataSet"];
 
       onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
 
       if (dsGrid == null)
       {
          dsGrid = GetDataSet( );
          string[] fileDependsArray = {Server.MapPath("Northwind.xml")};
          string[] cacheDependsArray = {"Depend0", "Depend1", "Depend2"};
          CacheDependency cacheDepends = new CacheDependency
                                (fileDependsArray, cacheDependsArray);
          Cache.Insert("GridViewDataSet", dsGrid, cacheDepends,
                        DateTime.Now.AddSeconds(10),
                        Cache.NoSlidingExpiration,
                        CacheItemPriority.Default,
                        onRemove);
          lblMessage.Text = "Data from XML file.";
       }
       else
       {
          lblMessage.Text = "Data from cache.";
       }
 
       gv.DataSource = dsGrid.Tables[0];
       gv.DataBind( );
    }
 
    private DataSet GetDataSet( )
    {
       DataSet dsData = new DataSet( );
       XmlDataDocument doc = new XmlDataDocument( );
       doc.DataSet.ReadXml(Server.MapPath("Northwind.xml"));
       dsData = doc.DataSet;
       return dsData;
    }
 
   public void RemovedCallback(string cacheKey,
                                 Object cacheObject,
                                 CacheItemRemovedReason reasonToRemove)
   {
      WriteFile("Cache removed for following reason: " +
         reasonToRemove.ToString( ));
   }
 
   private void WriteFile(string strText)
   {
      System.IO.StreamWriter writer = new System.IO.StreamWriter(
                                                   @"C:"test.txt", true);
      string str;
      str = DateTime.Now.ToString( ) + " " + strText;
      writer.WriteLine(str);
      writer.Close( );
   }
 
   protected void btnClear_Click(object sender, EventArgs e)
    {
      Cache.Remove("GridViewDataSet");
      CreateGridView( );
    }
 
   protected void btnInit_Click(object sender, EventArgs e)
   {
      // Initialize caches to depend on.
      Cache["Depend0"] = "This is the first dependency.";
      Cache["Depend1"] = "This is the 2nd dependency.";
      Cache["Depend2"] = "This is the 3rd dependency.";
   }
 
   protected void btnKey0_Click(object sender, EventArgs e)
   {
      Cache["Depend0"] = "This is a changed first dependency.";
   }
}

Table 17-5. Members of the CacheItemRemovedReason enumeration

Reason

Description

DependencyChanged

A file or item key dependency has changed.

Expired

The cached item has expired.

Removed

The cached item has been explicitly removed by the Remove method or replaced by another item with the same key.

Underused

The cached item was removed to free up system memory.

 

出处:http://www.cnblogs.com/leochu2008/articles/1161772.html

相关文章
相关标签/搜索