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

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

ASP.NET Cache缓存的使用的更多相关文章

  1. Asp.Net Cache缓存技术学习

    本文参考自Fish Li的细说 ASP.NET Cache 及其高级用法 一.前言,相信大多数做网站开发的都知道缓存技术对于网站的重要性,它对于网站的性能优化起着至关重要的作用. 关于缓存的技术大致有 ...

  2. ASP.NET Cache缓存的用法

    本文导读:在.NET运用中经常用到缓存(Cache)对象.有HttpContext.Current.Cache以及HttpRuntime.Cache,HttpRuntime.Cache是应用程序级别的 ...

  3. asp.net cache 缓存

    就是希望让Web应用程序从一开始运行到结束都一直存在,有人就说为什么不用Application呢?其实Cache是可以一段时间内自动更新数据的,而Application就无法做成这样的,另外Appli ...

  4. [转]ASP.NET cache缓存的用法

    本文转自:https://blog.csdn.net/mss359681091/article/details/51076712 本文导读:在.NET运用中经常用到缓存(Cache)对象.有HttpC ...

  5. ASP.NET状缓存Cache的应用-提高数据库读取速度

    原文:ASP.NET状缓存Cache的应用-提高数据库读取速度 一. Cache概述       既然缓存中的数据其实是来自数据库的,那么缓存中的数据如何和数据库进行同步呢?一般来说,缓存中应该存放改 ...

  6. ASP.NET -- WebForm -- 缓存Cache的使用

    ASP.NET -- WebForm --  缓存Cache的使用 把数据从数据库或文件中读取出来,放在内存中,后面的用户直接从内存中取数据,速度快.适用于经常被查询.但不经常变动的数据. 1. Te ...

  7. ASP.NET Core中使用Cache缓存

    ASP.NET Core中使用Cache缓存 缓存介绍: 通过减少生成内容所需的工作,缓存可以显著提高应用的性能和可伸缩性. 缓存对不经常更改的数据效果最佳. 缓存生成的数据副本的返回速度可以比从原始 ...

  8. Ajax跨域问题及解决方案 asp.net core 系列之允许跨越访问(Enable Cross-Origin Requests:CORS) c#中的Cache缓存技术 C#中的Cookie C#串口扫描枪的简单实现 c#Socket服务器与客户端的开发(2)

    Ajax跨域问题及解决方案   目录 复现Ajax跨域问题 Ajax跨域介绍 Ajax跨域解决方案 一. 在服务端添加响应头Access-Control-Allow-Origin 二. 使用JSONP ...

  9. ASP.NET 中HttpRuntime.Cache缓存数据

    最近在开始一个微信开发,发现微信的Access_Token获取每天次数是有限的,然后想到缓存,正好看到微信教程里面推荐HttpRuntime.Cache缓存就顺便看了下. 写了(Copy)了一个辅助类 ...

随机推荐

  1. ubuntu16.04的anacoda内置的spyder不支持中文【学习笔记】

    执行下面的语句:将libfcitxplatforminputcontextplugin.so复制到anaconda2的安装目录下的platforminputcontexts目录重启生效 cp /usr ...

  2. Spring Boot 设置启动时banner

    Spring Boot项目再启动的时候默认会在控制台输出一个字符banner图案,如下图: 我们可以通过下面的方法关闭启动时显示字符banner图案: 关闭banner方法一: public stat ...

  3. XML基本知识点——思维导图

    如图 思维导图图片链接 http://www.edrawsoft.cn/viewer/public/s/5dcd3224563939 有道云笔记图片链接 http://note.youdao.com/ ...

  4. c语言字符处理函数常见使用集合

    1.最近看一些开源项目代码时,总会看到 c 语言中一些  "str" 开头的处理字符串的用法,有的之前没用到过,特此记录,随时看到随时添加. 这里不提出源码,只是一些使用说明加例子 ...

  5. linux下fifo,mq,shm

    最近想为系统添加一个统计脚本,但是系统内的模块是有perl和java两种语言编写,且模块是通过crontab定时调用的,所以需要使用IPC传输信息. 第一个想到的是socket方式,感觉需要统一设定一 ...

  6. activity启动模式之singleTop

    activity启动模式之singleTop 一.简介 二.设置方法 在AndroidManifest.xml中将要设置为singleTop启动模式的页面进行配置 <activity andro ...

  7. CentOS下安装mysql及配置使用

    最近一直使用的是CentOS,平时用的最多的数据库是Sql Server,对于mysql还停留在上学的时候,早已忘得一干二净,写这篇内容目的是,重新学习如何安装使用mysql. 一.安装mysql 操 ...

  8. Ajax基础(一)--创建请求

    浏览器创建ajax请求: 1.如果是Firefox.Opera.Safari等高级浏览器,可使用XMLHttpRequest()方式创建一个新的ajax请求对象. 如果是IE浏览器,则使用Active ...

  9. gulp 相关文章

    1.https://www.cnblogs.com/sxz2008/p/6370221.html 2.https://www.cnblogs.com/wujie520303/p/4964931.htm ...

  10. 如何让vim 有颜色

    1.vi /root/.bashrc 下添加export TERM=xterm 2.同时 会话选项→仿真 勾选ANSI颜色 另外:上面如果不行,还修改了这个地方: vim ~/.vimrc synta ...