缓存的使用

一,客户端缓存

1.1 就是cookie

二 ,服务器端之 Asp.net缓存

2.1 Session

Session 对象保存和单个用户有关的数据,sessionid来区别是那个客户的session

2.2 Application

Application对象可保留和应用程序有关的数据,每个用户都可以访问。

2.3 System.Web.Caching

Cache 是线程安全的(线程安全是指:当一个线程访问它,其他线程就不可访问

Add() 方法插入一个键,如果多次Add相同数据,以第一次插入的数据为准

Insert()方法更新, 将覆盖有相同Key的Cache顶。

ICache cache1 = CacheFactory.Cache();
 cache1.Add<string>("test11", "test11", TimeSpan.FromMinutes(10));
 cache1.Add<string>("test111111", "test11", TimeSpan.FromMinutes(10)); //不起作用,也不报异常,以第一次为准 cache.GetCache<string>("test11") 还是test11
cache1.Update<string>("test11111", "test11"); //更新

Cache驱逐策略(即删除策略)--保证内存中的数据有个时效性

absoluteExpiration
类型:System.DateTime
所添加对象将到期并被从缓存中移除的时间。如果使用可调到期,则 absoluteExpiration 参数必须为 NoAbsoluteExpiration。

slidingExpiration
类型:System.TimeSpan
最后一次访问所添加对象时与该对象到期时之间的时间间隔。如果该值等效于 20 分钟,则对象在最后一次被访问 20 分钟之后将到期并从缓存中移除。如果使用绝对到期,则 slidingExpiration 参数必须为 NoSlidingExpiration。

Ps: cache类是全局的,静态的 

 

 

HttpRuntime.Cache.Add(

       KeyName,//缓存名

       KeyValue,//要缓存的对象

       Dependencies,//依赖项 ,通常为null

       AbsoluteExpiration,//绝对过期时间

       SlidingExpiration,//相对过期时间

       Priority,//优先级 System.Web.Caching.CacheItemPriority.Normal

       CacheItemRemovedCallback);//缓存过期引发事件

eg:

//最后一次访问所添加对象时与该对象到期时之间的时间间隔
cache.Add(cacheKey, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, timeSpan, System.Web.Caching.CacheItemPriority.Normal, null);

 

 

 

 

2.4 MemoryCache  --有点疑惑

System.Runtime.Caching.MemoryCache 和 HttpRuntime.Cache之间有什么区别?

  System.Web.Caching.Cache cache = HttpRuntime.Cache;

区别是前者已更改为使它可以由不是ASP.NET应用程序的.NET Framework应用程序使用。 MemoryCache 程序集没有依赖项 System.Web

另一差别在于,您可以创建类的多个实例, MemoryCache 以便在同一个应用程序和同一个实例中使用 AppDomain 。??

 

posted @ 2021-08-30 09:19  海龟123  阅读(41)  评论(0编辑  收藏  举报