System.Web.Caching
区别缓存和cookie不是同一个东西
cookie 是存放在客户端,缓存存放在服务器
C#
public Object Add(
string key,
Object value,
CacheDependency dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback
)
参数
key
类型:System.String
用于引用该项的缓存键。
value
类型:System.Object
要添加到缓存的项。
dependencies
类型:System.Web.Caching.CacheDependency
该项的文件依赖项或缓存键依赖项。当任何依赖项更改时,该对象即无效,并从缓存中移除。如果没有依赖项,则此参数包含 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing)。
absoluteExpiration
类型:System.DateTime
所添加对象将到期并被从缓存中移除的时间。如果使用可调到期,则 absoluteExpiration 参数必须为 NoAbsoluteExpiration。
slidingExpiration
类型:System.TimeSpan
最后一次访问所添加对象时与该对象到期时之间的时间间隔。如果该值等效于 20 分钟,则对象在最后一次被访问 20 分钟之后将到期并从缓存中移除。如果使用绝对到期,则 slidingExpiration 参数必须为 NoSlidingExpiration。
priority
类型:System.Web.Caching.CacheItemPriority
对象的相对成本,由 CacheItemPriority 枚举表示。缓存在退出对象时使用该值;具有较低成本的对象在具有较高成本的对象之前被从缓存移除。
onRemoveCallback
类型:System.Web.Caching.CacheItemRemovedCallback
在从缓存中移除对象时所调用的委托(如果提供)。当从缓存中删除应用程序的对象时,可使用它来通知应用程序。
返回值
类型:System.Object
备注
如果 Cache 中已保存了具有相同 key 参数的项,则对此方法的调用将失败。若要使用相同的 key 参数覆盖现有的 Cache 项,请使用 Insert 方法。
无法同时设置 absoluteExpiration 和 slidingExpiration 参数。如果要让缓存项在特定时间到期,可将 absoluteExpiration 参数设置为特定时间,并将 slidingExpiration 参数设置为 NoSlidingExpiration。
如果要让缓存项在最后一次访问该项后的某段时间之后到期,可将 slidingExpiration 参数设置为到期间隔,并将 absoluteExpiration 参数设置为 NoAbsoluteExpiration。
首先介绍它的Add()方法,将指定的对象添加到Cache对象集合中。
Insert()方法将覆盖有相同Key的Cache顶。
Remove()从应用程序的Cache对象中移除指定项。
Count属性,获取存储在缓存中对象数。
System.Web.Caching.Cache Cache = HttpRuntime.Cache; ArrayList myarray = new ArrayList(); //创建数组数据 myarray.Add("1.学习园地"); myarray.Add("2.交流论坛"); myarray.Add("3.帮助"); //将数组添加到缓存中——使用Add方法,insert 也可以达到相同的效果 // Cache.Add("Category", myarray, null, DateTime.Now.AddSeconds(120), TimeSpan.Zero, CacheItemPriority.Normal, null); Cache.Insert("Category", myarray, null, DateTime.Now.AddSeconds(120), TimeSpan.Zero, CacheItemPriority.Normal, null); myarray[1] = "2.交流园地"; //修改数组数据 Cache.Insert("Category", myarray); //使用Insert方法修改缓存数据,如果使用了add 则失败 string tmpStr = "这是一个临时数据"; Cache["tmpdata"] = tmpStr; //使用Get方法获取缓存数据 Response.Write(Cache.Get("tmpdata").ToString() + "<br/>"); Cache["tmpdata"] = "这是一个临时字符串"; //重新为缓存赋值的技巧 Response.Write(Cache.Get("tmpdata").ToString() + "<br/>"); //使用GetType方法判断缓存数据的类型 if (Cache["Category"].GetType().Name == "ArrayList") Response.Write("类型是数组"); //使用GetEnumerator方法遍历缓存中的数据 IDictionaryEnumerator mycache = Cache.GetEnumerator(); while (mycache.MoveNext()) Response.Write(mycache.Value + "<br/>"); Cache.Remove("tmpdata");//使用Remove方法移除缓存的临时数据