首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ASP.NET 缓存 Cache

ASP.NET 缓存 Cache

作者头像
磊哥
发布2018-04-26 16:48:43
1.3K0
发布2018-04-26 16:48:43
举报
文章被收录于专栏:王磊的博客王磊的博客

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 方法。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2010-10-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档