现在的位置: 首页 > 综合 > 正文

.NET cache的使用

2012年02月04日 ⁄ 综合 ⁄ 共 5479字 ⁄ 字号 评论关闭
一. Cache 是如何工作的。

Cache 是分配在服务器上的一个公共的内存片。

所谓公共指的cache只要一创建是任何一个客户端浏览器都可以通过后台代码访问到它,它面向的是所有用户,相对而言session也是服务器上的一段内存,但他面向的是单个用户。它是服务器的一段内存块,也就是说每个cache一经创建就占用了服务器资源的。所以从这点来说我们就可以说:并不是 cache越多越好。

cache 是有时间限制的,超过了服务器设定的过期时间,它就会被服务器回收。

cache 可以存放任何对象

二. Cache 如何创建以及如何销毁。

创建cache

在。Net环境下通过Cache.Insert(string key,object o)方法创建。其中key 代表cache的ID,o代表存到cache里的对象。

销毁cache.

通过方法Cache.Remove(string key)其中key 代表cache的 ID.

调用cache.

Cache支持装箱/拆箱操作。如你可以把一个DataSet对象ds通过Cache.Insert("dsCache",ds)的方式存到Cache中,可以通过拆箱操作 DataSet ds = (DataSet)Cache["dsCache"]来访问它。

三. 什么时候用cache.

Cache 一般用于数据较固定,用的较频繁的地方。例如可以把进销存系统中可以把产品信息存入cache,在用户调用产品信息时通过调用cache即可,这样从很大程度上减少了用户与数据库的交互,提高了系统的性能。反之,cache不适合用在数据变动快,使用范围很窄的地方。例如把一个具体采购单存入 cache中。

四. cache 调用注意事项。

Cache是有时间限制的。超过了服务器设置的过期时间,就会被服务器回收。当cache被回收后对应的内存块就会被清空,再次通过cache["cachekey"]访问对象时返回的就是null值。所以以下这种调用就会出现异常

DataSet ds = (DataSet)Cache["cacheds"];
DataRow dr = ds.Table[0].Row[0]; //出错,ds为null值,不存在表0。

五. cache的使用方法

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

1.缓存的添加:

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

Cache.Add(

       KeyName,//缓存名

       KeyValue,//要缓存的对象

       Dependencies,//依赖项

       AbsoluteExpiration,//绝对过期时间

       SlidingExpiration,//相对过期时间

       Priority,//优先级

       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.";

   }

}

抱歉!评论已关闭.