ASP.NET 提供一个功能完整的缓存引擎,页面可使用该引擎通过 HTTP 请求存储和检索任意对象.
缓存的生存期与应用程序的生存期相同,也就是说,当应用程序重新启动时,将重新创建缓存。

将数据添加到缓存中

1。通过指定其键和值将项添加到缓存中
Cache["txt"] = "a";

2.通过使用 Insert(重载Insert方法)方法将项添加到缓存中

Cache.Insert("txt", "a");

下列代码显示如何设置相对过期策略。它插入一个项,该项自上次访问后 10 分钟过期。注意 DateTime.MaxValue 的使用,它表示此项没有绝对过期策略。

DateTime absoluteExpiration=DateTime.MaxValue;
TimeSpan slidingExpiration=TimeSpan.FromMinutes(10);
Cache.Insert("txt", "a",null,
absoluteExpiration,slidingExpiration,
System.Web.Caching.CacheItemPriority.High,null);

3.使用 Add 方法将项添加到缓存中
Add 方法与 Insert 方法具有相同的签名,但它返回表示您所添加项的对象

DateTime absoluteExpiration=DateTime.MaxValue;
TimeSpan slidingExpiration=TimeSpan.FromMinutes(10);
Object  Ojb=(string)Cache.Add("txt","a",null,
absoluteExpiration ,slidingExpiration ,
System.Web.Caching.CacheItemPriority.High,null);
string str=(string)Ojb ;
Response.Write(str);

结果显示是"a"

Add 方法使用上没有Insert 方法灵活,使用Add 方法时必须提供7个参数,Insert 方法重载4次,我们可以根据需要选择适当重载方法

从缓存中取得数据

方式1:
string str=(string)Cache.Get("txt");
Response.Write(str);

方式2:
string str1=(string)Cache["txt1"];
Response.Write(str1);

查看Cache中所有数据

System.Text.StringBuilder sb=new System.Text.StringBuilder("",100);
foreach(DictionaryEntry Caches  in Cache)
{
sb.Append("key=").Append(Caches.Key.ToString()).Append("
") ;
sb.Append("value=").Append(Caches.Value.ToString()).Append("
");
}
Response.Write(sb.ToString());

查看Cache中的项数

int Count=Cache.Count;
Response.Write(Count.ToString());

将数据从缓存中删除

Cache.Remove("txt");

使Cache具有文件依赖项或键依赖项的对象

我们在一页面建立1个按钮,查看CACHE是否存在
在窗体启动时我们创建CACHE,名称="txt2",数值=数据集ds
该CACHE与myfile.xml相关联,当myfile.xml文件变化时,txt2CACHE就被自动删除

private void Page_Load(object sender, System.EventArgs e)
{
if( !IsPostBack  )
{
string FilePath=MapPath("myfile.xml");
SqlConnection con=new SqlConnection("Uid=sa;database=pubs;");
SqlDataAdapter da =new SqlDataAdapter("select * from authors",con);
DataSet ds=new DataSet();
da.Fill(ds);
System.Web.Caching.CacheDependency CacheDependencyXmlFile=new System.Web.Caching.CacheDependency(FilePath);
Cache.Insert("txt2",ds ,CacheDependencyXmlFile);
}
}

为了监视pubs数据库authors表的变化
我们可以在pubs数据库authors表建立触发器
一旦authors表中发生增加,删除,修改数据时,触发器会自动修改文件myfile.xml
一旦myfile.xml文件变化,txt2CACHE就被系统自动删除

CREATE TRIGGER tr_authors
ON authors
FOR INSERT, UPDATE ,delete
AS
declare @cmd nvarchar(4000)
select @cmd='bcp "select convert(nvarchar(30),Getdate(),13)" queryout D:\cache\WebCache\myfile.xml -c -Sglc2403 -Usa -P'
exec master..xp_cmdshell @cmd
GO

private void QueryButton_Click(object sender, System.EventArgs e)
{
if ( Cache["txt2"]!=null)
{
Response.Write("exists");
}
else
{
Response.Write("not exists");
}
}

首先我们点按钮,显示Cache["txt2"]存在
现在我们去表authors中任意修改一数据,再点按钮,显示Cache["txt2"]不存在拉

以上我们是把CACHE是和一个文件相关联,我们还可以把CACHE和文件组关联,建立依赖
以下我们把CACHE和2个文件(myfile.xml,myfile1.xml)关联,一旦文件组中其中任意一文件变化,Cache会把"txt2"项的数据从CACHE中删除

string[] FilePath=new String[]{MapPath("myfile.xml"),MapPath("myfile1.xml")};
System.Web.Caching.CacheDependency CacheDependencyXmlFile=new                     System.Web.Caching.CacheDependency(FilePath);
string CacheVaule="a";
Cache.Insert("txt2", CacheVaule ,CacheDependencyXmlFile);

缓存依赖可以是文件,还可以是其他对象的键
下面的代码说明缓存Cache["txt2"]既依赖文件myfile.xml,又依赖缓存中的Cache["txt"],只要这2者任意一样改变,缓存Cache["txt2"]就会清除

Cache["txt"] = "b";
string[] FilePath=new String[]{ MapPath("myfile.xml")};
string[] dependencyKey=new String[]{"txt"};
SqlConnection con=new SqlConnection("Uid=sa;database=pubs;");
SqlDataAdapter da =new SqlDataAdapter("select * from authors",con);
DataSet ds=new DataSet();
da.Fill(ds);
System.Web.Caching.CacheDependency CacheDependencyXmlFile=
new System.Web.Caching.CacheDependency(FilePath,dependencyKey);
Cache.Insert("txt2",ds ,CacheDependencyXmlFile);

缓存绝对过期

缓存Cache["txt3"] 在1小时后自动过期
DateTime absoluteExpiration =DateTime.Now.AddHours(1);
Cache.Insert("txt3","aa",null,absoluteExpiration,System.Web.Caching.Cache.NoSlidingExpiration);

缓存相对(滑动)过期

注意:如果创建的弹性到期时间小于零或大于一年,则将引发异常
缓存Cache["txt4"] 在最后一次被访问后1小时自动过期
TimeSpan slidingExpiration=TimeSpan.FromHours(1);
Cache.Insert("txt4","4",null,System.Web.Caching.Cache.NoAbsoluteExpiration,slidingExpiration);

缓存项的优先等级

当承载 ASP.NET 应用程序的 Web 服务器缺少内存时,Cache 将有选择地清除项来释放系统内存。当向缓存添加项时,可以为其分配与缓存中存储的其他项相比较的相对优先级。在服务器处理大量请求时,分配了较高优先级值 的项被从缓存删除的可能性较小,而分配了较低优先级值的项则更有可能被删除。
由CacheItemPriority 枚举表示,默认为 Normal。

缓存Cache["txt5"]优先等级设为最高等级,在服务器释放系统内存时,该缓存项最不可能被删除。
Cache.Insert("txt5","5",null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.High,null);

缓存项时通知应用程序的回调方法

ASP.NET 提供 CacheItemRemovedCallback 委托。它定义编写事件处理程序时使用的签名,当从缓存中删除项时,该事件处理程序将进行响应。

static System.Web.Caching.CacheItemRemovedReason reason;
System.Web.Caching.CacheItemRemovedCallback onRemove = null;

public void RemovedCallback(String k, Object v, System.Web.Caching.CacheItemRemovedReason r)
{
itemRemoved = true;
reason = r;
}

onRemove = new System.Web.Caching.CacheItemRemovedCallback (this.RemovedCallback);
Cache.Insert("txt",ds,null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Default,onRemove);

由于任何原因从Cache中移除时,将调用 RemovedCallback 方法。

ASP.NET 缓存 Cache相关推荐

  1. ASP.NET缓存 Cache

    ASP.NET缓存 Cache 缓存介绍 如果每次进入页面的时候都查询数据库生成页面内容的话,如果访问量非常大,则网站性能会非常差, 而如果只有第一次访问的时候才查询数据库生成页面内容,以后都直接输出 ...

  2. ASP.NET缓存 Cache之数据缓存

    添加 Cache[Key]=object  or Cache.Insert 移除 Cache.Remove(key) 1.将值直接写入Cache  代码如下 复制代码 HttpContext.Curr ...

  3. asp.net 缓存Cache的使用总结

    1).获取缓存值 object o = HttpRuntime.Cache.Get("Key"); 2).设置相对过期缓存值有两种写法 第一种: HttpRuntime.Cache ...

  4. asp.net 应用数据缓存 -- Cache对象使用

    ASP.NET 应用数据缓存 -- Cache对象使用 [原文:http://msdn.microsoft.com/zh-cn/library/18c1wd61%28v=vs.100%29.aspx] ...

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

    ASP.NET状缓存Cache的应用-提高数据库读取速度 原文:ASP.NET状缓存Cache的应用-提高数据库读取速度 一. Cache概述        既然缓存中的数据其实是来自数据库的,那么缓 ...

  6. ASP.NET状态管理之六(缓存Cache)

    ASP.NET状态管理之六(缓存Cache) ASP.NET 为您提供了一个强大的.便于使用的缓存机制,用于将需要大量服务器资源来创建的对象存储在内存中.缓存这些类型的资源会大大改进应用程序的性能. ...

  7. ASP.NET缓存中Cache过期的三种策略

    ASP.NET缓存中Cache过期的三种策略 原文:ASP.NET缓存中Cache过期的三种策略 我们在页面上添加三个按钮并双击按钮创建事件处理方法,三个按钮使用不同的过期策略添加ASP.NET缓存. ...

  8. 浅谈ASP.NET 缓存技术

    缓存是指系统或应用程序将频繁使用的数据保存到内存中,当系统或应用程序再次使用时,能构快速的获取数据.它的弊端在于显示的内容可能不是最新,最精确的.ASP.Net 缓存主要分为两大类: 网页输出缓存和应 ...

  9. petshop4.0 详解之四(PetShop之ASP.NET缓存)

    <p>如果对微型计算机硬件系统有足够的了解,那么我们对于Cache这个名词一定是耳熟能详的.在CPU以及主板的芯片中,都引入了这种名为高速缓冲存储器(Cache)的技术.因为Cache的存 ...

最新文章

  1. Error writing file '/tmp/...' (Errcode: 28)
  2. 云服务器centos登录日志文件,云服务器centos登录日志文件
  3. Hha mysql_libmySQL.dll
  4. angularjs1访问子组件_Vue学习笔记之组件的应用
  5. ubuntu下IP、DNS配置
  6. siege4安装和使用介绍
  7. window.location.href 跳转失败
  8. numpy: np.random.get_state()
  9. JQuery版本下载链接
  10. 底量超顶量超级大黑马指标源码_通达信绝密三代指标,秒杀一切妖股指标公式源码...
  11. ESP32上手笔记 | 05 - 获取MPU6050数据进行姿态解算和展示(I2Cdev+MPU6050+Processing)
  12. Proof of Stake FAQ
  13. 长链亲脂性二烷基碳菁类染料DiR iodide,DiR细胞膜染料,100068-60-8
  14. 老七苏-37:明日之星 苏-37是在苏-35的基础上改进而成的。
  15. [js点滴]JavaScript基础正则详解03
  16. 纤亿通带你了解GPON和EPON的区别
  17. 图片切割 - 九宫格
  18. tomcat禁止访问路径与文件、错误页面跳转配置
  19. 前端之移动web开发(下)
  20. Java基础教程1-Java特点和手把手教你安装JDK

热门文章

  1. Iptables防火墙原理
  2. Scala中class与object区别
  3. wordpress后台无法登录问题
  4. C#组成考题字符串【C#】
  5. FreeSWITCH的TLS加密
  6. Java高质量代码之 — 泛型与反射
  7. VTP实现VLAN同步
  8. 一些算法题,欢迎来改进
  9. Android系统进程间通信(IPC)机制Binder中的Client获得Server远程接口过程源代码分析(2)...
  10. 更新MySQL复制 自动监控脚本