博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ObjectCache 的使用
阅读量:6983 次
发布时间:2019-06-27

本文共 1961 字,大约阅读时间需要 6 分钟。

Cache的获取及定义

Cache的获取代码:

var cache = CacheManager.Instance.GetCache<KeyType, ValueType>();

因此对Cache的定义,实际上就是对KeyType和ValueType的定义,例如:

class Key :IEquatable
{public string Id{get;set;}public bool Equals(Key other){ if(other == null) return false; return Id == other.Id;}class BusinessObj{ /* property definitions*/}

有了以上两个类型,我们就可以用来创建/获取cache了。

var cache = CacheManager.Instance.GetCache<Key, BusinessObj>();

 

Cache的作用范围

由于Cache的定义实际上是通过强类型来定义的,如上面的代码GetCache<Key, BusinessObj>()。因此Cache的作用范围等同于上面定义的类型Key和BusinessObj的作用范围。

Cache生命周期的管理

Cache生命周期的管理问题实际上就是控制cache的内容在何时失效。

有以下两种方式来控制cache内容何时失效,cache的内容一旦失效,它就会被从内存中移除

1. 可以通过继承BaseToken来管理

2. 直接调用ICache上的Reset()方法来清空Cache中的所有内容

3. 直接调用ICache上的Remove()方法来指定移除某一个CacheItem

Cache的分组

对Cache分组的目的是,我们可以对同一组别的Cache进行清空处理。Cache的分组信息通过特性定义在Cache的Key上面。请参见以下代码:

[CacheKeyCategory(2)]        class CackeKey2 : IEquatable
{ public long Id { get; set; } #region IEquatable
Members public bool Equals(CackeKey2 other) { return Id == other.Id; } #endregion }

我们可以通过如下单元测试来看清楚其作用

[TestMethod]        public void CacheCategory_Category_Test()        {            var cache = CacheManager.Instance.GetCache
(); cache.GetWithCreate(new CackeKey2 { Id = 1 }, () => "Hello", new BaseToken()); Assert.AreEqual(1, cache.Count()); CacheManager.Instance.ResetCaches(4); Assert.AreEqual(1, cache.Count()); CacheManager.Instance.ResetCaches(2); Assert.AreEqual(0, cache.Count()); }
当CacheManager.Instance.ResetCaches(4)被调用时,Cache<CacheKey2,string>中的内容并没有被清空。当

CacheManager.Instance.ResetCaches(2)被调用时,Cache<CacheKey2,string>中的内容才被清空。

如果Cache的key没有添加分组信息,那么只有当CacheManager.Instance.ResetCaches(0);被调用时,Cache中的内容才会被清空,且实际上,这是所有的缓存都会被清空。

转载于:https://www.cnblogs.com/czy/archive/2012/01/10/2318150.html

你可能感兴趣的文章
RAC 11.2的新特性
查看>>
2星|《金融学从入门到精通》:金融学名词解释的堆砌
查看>>
数据库四种事务隔离级别
查看>>
基于模板的excel导出
查看>>
基于Nginx负载均衡方案
查看>>
双活数据中心
查看>>
python练习题
查看>>
cut命令
查看>>
powershell最常用的命令之(一)
查看>>
LAMP一键安装脚本
查看>>
linux之打补丁
查看>>
phpexcel
查看>>
使用logrotate实现日志轮训压缩
查看>>
centos下解决nginx 无法连接gitlab socket
查看>>
What is Citrix X1
查看>>
华为OSPF配置
查看>>
Win8 Metro(C#)数字图像处理--2.63图像指数增强
查看>>
Expect-自动化交互
查看>>
SCCM 2012 SP1系列(一)先决条件准备-1
查看>>
shell 逻辑运算符、逻辑表达式详解
查看>>