MemoryCache缓存 ---缓存时效测试

var cachePool = new MyCachePool();
//Thread.Sleep(1000);
var value = cachePool.GetFileValue();

/// <summary>
/// MemoryCache缓存
/// </summary>
public class MyCachePool
{
ObjectCache cache = MemoryCache.Default;
const string cacheKey = "TestCacheKey";
public string GetValue()
{
var content = cache[cacheKey] as string;
if (content == null)
{
//Console.WriteLine("Get New Item"); var policy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddSeconds() };
content = Guid.NewGuid().ToString();
cache.Set(cacheKey, content, policy);
}
else
{
Console.WriteLine("Get cached item");
} return content;
}
public string GetFileValue()
{
string strCacheKey = "FileCacheKey";
var content = cache[strCacheKey] as string;
if (content == null)
{
//Console.WriteLine("Get New Item"); //var file = @"E:\test.txt";
//CacheItemPolicy policy = new CacheItemPolicy();
//policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { file })); //content = File.ReadAllText(file);
//cache.Set(strCacheKey, content, policy); CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(); content = Guid.NewGuid().ToString(); CacheItem item = new CacheItem("cachedText", content); List<string> keys = new List<string> { strCacheKeyChange }; policy.ChangeMonitors.Add(cache.CreateCacheEntryChangeMonitor(keys)); //依赖某个值变化 cache.Set(item, policy);
}
else
{
Console.WriteLine("Get cached item");
} return content;
}
}

缓存用起来也就是通过Key来增删改查,内存缓存还可以在config中的配置对内存的使用情况

/// <summary>
/// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存
/// </summary>
/// <param name="cacheKey">缓存Key</param>
/// <returns>配置词典</returns>
private static Dictionary<string, string> GetConfigDictionary(string cacheKey)
{
Dictionary<string, string> configs = null; //1、获取内存缓存对象
ObjectCache cache = MemoryCache.Default; //2、通过Key判断缓存中是否已有词典内容(Key在存入缓存时设置)
if (cache.Contains(cacheKey))
{
//3、直接从缓存中读取词典内容
configs = cache.GetCacheItem(cacheKey).Value as Dictionary<string, string>;
}
else
{
//3、读取配置文件,组成词典对象,准备放到缓存中
configs = GetFromXml(); //4、检查是否读取到配置内容
if (configs != null)
{
//4、新建一个CacheItemPolicy对象,该对象用于声明配置对象在缓存中的处理策略
CacheItemPolicy policy = new CacheItemPolicy(); //5、因为配置文件一直需要读取,所以在此设置缓存优先级为不应删除
// 实际情况请酌情考虑,同时可以设置AbsoluteExpiration属性指定过期时间
policy.Priority = CacheItemPriority.NotRemovable; //6、将词典内容添加到缓存,传入 缓存Key、配置对象、对象策略
// Set方法首先会检查Key是否在缓存中存在,如果存在,更新value,不存在则创建新的
// 这里先加入缓存再加监视的原因是:在缓存加入时,也会触发监视事件,会导致出错。
cache.Set(cacheKey, configs, policy); //7、监视文件需要传入一个IList对象,所以即便只有一个文件也需要新建List对象
List<string> filePaths = new List<string>() { "c:\config.xml" }; //8、新建一个文件监视器对象,添加对资源文件的监视
HostFileChangeMonitor monitor = new HostFileChangeMonitor(filePaths); //9、调用监视器的NotifyOnChanged方法传入发生改变时的回调方法
monitor.NotifyOnChanged(new OnChangedCallback((o) =>
{
cache.Remove(cacheKey);
}
)); //10、为配置对象的缓存策略加入监视器
policy.ChangeMonitors.Add(monitor);
}
}
return configs;
}

MemoryCache缓存 ---缓存时效的更多相关文章

  1. 基于MemoryCache的缓存辅助类

    背景: 1. 什么是MemoryCache? memoryCache就是用电脑内存做缓存处理 2.使用范围? 可用于不常变的数据,进行保存在内存中,提高处理效率 代码: /// <summary ...

  2. 在.NET项目中使用PostSharp,使用MemoryCache实现缓存的处理(转)

    在之前一篇随笔<在.NET项目中使用PostSharp,实现AOP面向切面编程处理>介绍了PostSharp框架的使用,试用PostSharp能给我带来很多便利和优势,减少代码冗余,提高可 ...

  3. 在.NET项目中使用PostSharp,使用MemoryCache实现缓存的处理

    在之前一篇随笔<在.NET项目中使用PostSharp,实现AOP面向切面编程处理>介绍了PostSharp框架的使用,试用PostSharp能给我带来很多便利和优势,减少代码冗余,提高可 ...

  4. .Net Core缓存组件(MemoryCache)【缓存篇(二)】

    一.前言 .Net Core缓存源码 1.上篇.NET Core ResponseCache[缓存篇(一)]中我们提到了使用客户端缓存.和服务端缓存.本文我们介绍MemoryCache缓存组件,说到服 ...

  5. EhCache RMI 分布式缓存/缓存集群

    EhCache 系统简介 EhCache 是一个纯 Java 的进程内缓存框架,具有快速.精干等特点. EhCache 的主要特性有: 快速.精干 简单: 多种缓存策略: 缓存数据有两级:内存和磁盘, ...

  6. EhCache 分布式缓存/缓存集群

    开发环境: System:Windows JavaEE Server:tomcat5.0.2.8.tomcat6 JavaSDK: jdk6+ IDE:eclipse.MyEclipse 6.6 开发 ...

  7. EhCache 分布式缓存/缓存集群(转)

    开发环境: System:Windows JavaEE Server:tomcat5.0.2.8.tomcat6 JavaSDK: jdk6+ IDE:eclipse.MyEclipse 6.6 开发 ...

  8. HTTP缓存缓存机制

    http协议无状态,所以缓存设定从两方面考虑.客户端浏览器和服务器端. 浏览器端实现过期机制. 服务器端实现验证机制. 缓存机制. 为了减轻服务器负担,也减少网络传输数量.http1.0定义了Expi ...

  9. Unity3D性能优化小tips——把this.transform缓存缓存起来

    Unity3D开发时中有一个小tips,这在官方的文档里其实有提及的,但不那么显眼,这里小说一下: 在MonoBehaviour进行编程时,我们经常会用this.transform, this.gam ...

随机推荐

  1. Metasploit 读书笔记-持久控制

    Meterpreter的persisitence脚本允许主任meterpreter代理,以确保系统重启之后Meterpreter还能运行。如果是反弹连接方式,可以设置连接攻击机的时间间隔。如果是绑定方 ...

  2. 【2】循序渐进学 Zabbix:安装配置 Zabbix Server 服务端

    上一篇 [1]循序渐进学 Zabbix :初识与基础依赖环境搭建( LNMP ) 安装 Zabbix Server 上篇我们在 192.168.200.101 上面安装了 Zabbix 所依赖的 LN ...

  3. 使用jenkins来跑docker image的惨痛经历

    记录一下我使用jenkins来跑docker container的艰辛路程吧,是照着jenkins官网的[文档](https://jenkins.io/doc/tutorials/build-a-ja ...

  4. Spark大数据处理 之 动手写WordCount

    Spark是主流的大数据处理框架,具体有啥能耐,相信不需要多说.我们开门见山,直接动手写大数据界的HelloWorld:WordCount. 先上完整代码,看看咋样能入门. import org.ap ...

  5. 老男孩Day6作业:计算器

    作业需求: 1.实现加减乘除及拓号优先级解析 2.用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) ...

  6. linux进程切换问题

    #define switch_to(prev,next,last) do { \ unsigned long esi,edi; \ asm volatile("pushfl\n\t" ...

  7. README.md使用

    1.标题: # 一级标题 ## 二级标题 ### 三级标题 2.换行: <br> 3.代码: ``` 代码在中间 ``` 4.表格: 表头 | 表头 | 表头 ---- | ----- | ...

  8. VS2008 生成的程序有管理员权限

    vs 2008 . 解决方案---右键属性----连接器---清单文件---UAC执行级别---设置为requireAdministrator

  9. html 一些坑。。。

    margin-left 和 margin-right 才能够使用 auto top 和 bottom 不可以 在网页设计中...通常给img 父容器 一个 宽度...同时 ,指定 img width= ...

  10. Codeforces Round #316 (Div. 2) A

    Description The country of Byalechinsk is running elections involving n candidates. The country cons ...