原文:HttpContext.Current.Cache 过期时间

为了更快的读取数据,我们一般会把常用到的数据加载到Cache中

在.NET中,Cache的存在可以依赖多中方式,主要用到HttpContext.Current.Cache类


在这里,我主要写几种依赖方式

1:不依赖任何条件


HttpContext.Current.Cache.Insert(string cacheName,object obj)


理论上是Cache会永久保存,但是当服务器重新启动,内存紧张的时候也会丢失.


2:HttpContext.Current.Cache.Insert(string key, object value,
CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan
slidingExpiration);


//CacheDependency缓存依赖项,absoluteExpiration绝对过期时间,slidingExpiration最后一次访问的时间隔


//我们主要讲两种Cache依赖

2.1:文件依赖,so simple//只要文件改动,Cache移出


HttpContext.Current.Cache.Insert(cacheName,ojb, new
System.Web.Caching.CacheDependency(FilePath));


2.2:SqlServer数据库依赖//我这里是SQL2005

首先看数据库通知是否可用,记得一定要开启通知


Select DATABASEpRoPERTYEX('数据库名','IsBrokerEnabled');如果值为1表示可用


alter database Game176Admin set ENABLE_BROKER ;//开启
alter database
Game176Admin set DISABLE_BROKER;//关闭

在Global.asax文件中,我们在应用程序开始和结束时要做一些事情


void Application_Start(object sender, EventArgs e)
{

// 在应用程序启动时运行的代码
try
{

System.Data.SqlClient.SqlDependency.Start(string strCon);//开启
}

catch { }
}

void Application_End(object sender,
EventArgs e)
{
// 在应用程序关闭时运行的代码
try

{
System.Data.SqlClient.SqlDependency.Stop(string strCon);

}
catch { }
}

准备工作已经完成

我们先写一个方法,添加数据库依赖


void AddSqlDependency(string strCon, string strSql,
OnChangeEventHandler sqlDep_OnChange)
{
try

{
using (SqlConnection conn = new
SqlConnection(strCon))
{
SqlCommand
comm = new SqlCommand(strSql, conn);
SqlDependency sqlDep
= new SqlDependency(comm);
sqlDep.OnChange +=
sqlDep_OnChange;
if (conn.State ==
ConnectionState.Closed) conn.Open();

comm.ExecuteNonQuery();
}
}

catch (Exception ex)
{

LogUtility.Add(ex);
}
}


//上面这个方法是告诉数据库,当你指定表数据改变,要移出缓存

我们现在可以来添加了

MyObject obj= HttpRuntime.Cache["cacheName"] as MyObject;
if
(null == obj)
{
try

{
obj= GetObj(...);
}

catch (Exception ex)
{

LogUtility.Add(ex);
obj= null;

}
if (null != obj)

{
AddSqlDependency(strCon, "select id from
dbo.tableName;select id1 from dbo.tableName1",

delegate(object sender, SqlNotificationEventArgs e)

{
//do something

HttpRuntime.Cache.Remove("cacheName");
});

HttpRuntime.Cache.Insert("cacheName", obj);

}
}


上面SQL语句中用到的表,只要这些表中的任何数据有改动,数据库都会通知,这时缓存会移动,select的字段和Cache没有关系,只有表名有关系,所有你要选择最小的字段.很多时候,为了这个字段,在设计表的时候都为多加一个最小的依赖列.


NOTE:任何Cache都可能丢失,使用前一定要做必要的检查,如:

MyObject
obj=HttpContext.Current.Cache("CacheName") as MyObject;

if(null==obj)


{

obj=.......

HttpContext.Current.Cache.Insert("CacheName",obj);

}
Cache用法之页面声明


<%@
outputCache
Duration="#ofseconds"
Location="Any|Client|Downstream|Server|None"
VaryByControl="ControlName"
VaryByCustom="browser|customstring"
VaryByHeader="headers"
VaryByParam="Parametername"
%>


Cache用法之代码控制
HttpCachePolicy类是专门用来控件Cache的,可以用Response.Cahce来访问这个类的实例


Response.Cache.SetExpires(DateTime.Now.AddSeceonds(10));
Response.Cache.SetCacheability(HttpCacheablility.Public);
Response.Cache.SetValidUnitlExpires(true);


-----------------------以上都是缓存页面的,下面是缓存数据的----------------------------
Cache
类的生存周期等于应用程序的生命周期
三种用法
1:存:Cache["key"] = MyData;取:
MyData =
Cache["key"];
if(MyData != null)

use(MyData);
此法存入Cache的数据生命周期等于应用程序生命周期,不支持清除、过期、依赖性等功能。


2:存:
Cache.Insert(
string key,
object value,
CacheDependency
dependencies,//依赖,设置缓存有效的依赖性,比如设置和一个文件相关,文件一变,就失效
DateTime
absoluteExpireation, //设置固定的过期时间
TimeSpan slidingExpiration,
//设置最后一次访问后多长时间过期
CachePriority priority,
//设置内存不足,缓存自动清除时,缓存的重要性,可不可以清除
CacheItemRemovedCallback onRemoveCallback //
设置在清除时引发的事件
)
Example:

Cache.Insert("Mydata",MyData,new
Caching.CacheDependency(Server.MapPah("Mydata.XML")));//设置有效性和一个文件有关
Cache.Insert("Mydata",myData,null,DateTime.Now.AddDays(1),Cache.NoSlidingExpiratin);//两种过期时间设了其中一种,另一种要设为0,用NoAbsolute(Sliding)Expiration枚举
Cache.Insert("MyData",myData,null,Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(10));//不能过一年不能小于0
Cache.Insert("MyData",myData,null,Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(10),

Caching.CacheItemPriority.NotRemovable,null);
//
AboveNormal|BelowNormal|Default|High|Low|Normal|NotRemovable

public void
RemovedCallback(string key,object value,CacheItemRemovedReason
reason)
{
if(reason == CacheItemRemovedReason.DependencyChanged)

Response.Write("文件变了,快去看看");
}
Cache.Insert("Mydata",MyData,new
Caching.CacheDependency(Server.MapPah("Mydata.XML"),

DateTime.Now.AddDays(1),Cache.NoSlidingExpiration,CacheItemPriority.High,

new CacheItemRemovedCallback(this.RemovedCallback));


清除就可以用Cache.Remove("key");方法


3:
Cache.Add方法,用法和Insert差不多,区别在于Add碰到该key原来有赋过值会失败,Insert则不会,而会替换原有值;Add会返回被缓存数据项,Insert不会

HttpContext.Current.Cache 过期时间的更多相关文章

  1. Asp.net中的Cache--HttpRuntim.Cache 和 HttpContext.Current.Cache

    在ASP.NET中有两个类都提供缓存支持, 一个是HttpRuntime类的Cache属性, 另一个是HttpContext类的Cache属性. 通过查看这两个属性的类型可以发现其实这两个属性都是Sy ...

  2. Cache及(HttpRuntime.Cache与HttpContext.Current.Cache)

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/avon520/archive/2009/11/25/4872704.aspx .NET中Cache有两种调用方式:Ht ...

  3. HttpContext.Current.Cache使用文件依赖问题

    HttpContext.Current.Cache.Insert("FCacheMs", tb, New CacheDependency(HttpContext.Current.S ...

  4. 缓存 HttpContext.Current.Cache和HttpRuntime.Cache的区别

    先看MSDN上的解释: HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象. HttpRuntime.Cache:获取当前应用程序的Cache.  我们再用. ...

  5. HttpContext.Current.Cache 和HttpRuntime.Cache的区别

    先看MSDN上的解释:      HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象.      HttpRuntime.Cache:获取当前应用程序的Cac ...

  6. HttpContext.Current.Cache 和 HttpRuntime.Cache 区别

    原文地址:http://blog.csdn.net/avon520/article/details/4872704 .NET中Cache有两种调用方式:HttpContext.Current.Cach ...

  7. HttpContext.Current.Cache 和 HttpRuntime.Cache

    HttpRuntime.Cache:用于winfrom 和 web HttpContext.Current.Cache 用于web .NET中Cache有两种调用方式:HttpContext.Curr ...

  8. HttpContext.Current.Cache和HttpRuntime.Cache的区别,以及System.Runtime.Caching

    先看MSDN上的解释:      HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象.      HttpRuntime.Cache:获取当前应用程序的Cac ...

  9. HttpRuntime.Cache 与 HttpContext.Current.Cache

    1.HttpRuntime.Cache是应用程序级别的, 2.而HttpContext.Current.Cache是针对当前WEB上下文定义的. 3.这二个都是调用的同一个对象,不同的是:HttpRu ...

随机推荐

  1. 转:说说JSON和JSONP

    前言 由于Sencha Touch 2这种开发模式的特性,基本决定了它原生的数据交互行为几乎只能通过AJAX来实现. 当然了,通过调用强大的PhoneGap插件然后打包,你可以实现100%的Socke ...

  2. 通过Wmi实现Hyper-V远程管理(一)

    最近公司需要做Hyper-V的远程管理,在现有产品基础上扩展对Hyper V的管理,实现远程开关机.远程开启虚拟机会话,其他内容可查看MSDN中有对Hyper-V的描述和相关实例代码. Wmi操作hy ...

  3. Android平台对H264视频硬解码

    本文讲述如何使用Android标准的API (MediaCodec)实现H264的硬件解码. 原本我们是用JNI调用平台提供的硬件解码接口得到YUV帧,再放入opengl脚本里处理渲染的.可是换了新平 ...

  4. Azure File SMB3.0文件共享服务(3)

    在Windows上使用Azure文件共享服务 之前简单介绍过,你可以通过SMB 3.0协议,将Azure文件共享挂载在本地,就如使用一个网络驱动器是一样的,但需要注意不同版本的Windows对于SMB ...

  5. Android ListView A~Z快速索引(改进版)

    上一篇文章虽然实现了ListView 快速索引的效果,但是有一个小小的Bug.这个Bug我在前面也说了,这篇文章就来解决这个Bug. 我研究的时候发现只要showBg值为true,中间的字母就显示,而 ...

  6. c++11介绍

    C++11标准是 ISO/IEC 14882:2011 - Information technology -- Programming languages -- C++ 的简称[1]  . C++11 ...

  7. Node.js 参考学习地址

    前段时间研究过Node.js 自从由于笔记本硬盘崩了之后就很少在家里搞程序了,但是很想学习之,只因最近在努力学习英文.技术之外的事也需要做好,我们毕竟不是为了技术而生,技术是我们生存的一门得力技能,唯 ...

  8. OSCHina技术导向:Java模板引擎velocity

    OSChina 采用 velocity 作为页面模板 Velocity是一个基于java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template langua ...

  9. 【HDU 2013 猴子吃桃子】 尾递归与迭代

    大一时的一道C语言练习题,可作为递归和尾递归转迭代的范例.HDU 2013 http://acm.hdu.edu.cn/showproblem.php?pid=2013 题意:猴子摘了sum个桃子,从 ...

  10. Web服务器压力测试一例

    近期部门新上线一个服务,我们使用ab和locust分别测试 目前项目属于demo阶段,对访问量的支持不要求太高,我们暂且设定在500请求,20并发 工具介绍 ab ab全称为:Apache HTTP ...