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. AngularJs 指令 directive中link,controller 的区别

    其实严格来讲,link和controller是完全不同的概念,这里讲区别有点牵强. angular指令中,带有link和controller两个函数,很多人在写指令的时候不知道是写在link里 还是c ...

  2. CSS之字体样式

    css字体样式 font-size:字号大小 font-size属性用于设置字号,该属性的值可以使用相对长度单位,也可以使用绝对长度单位.其中,相对长度单位比较常用,推荐使用像素单位px,绝对单位使用 ...

  3. luogu3327 [SDOI2015]约数个数和

    link 设\(d(x)\)表示x约数个数,给定n,m,\(\sum_{i=1}^n\sum_{j=1}^md(ij)\) 多组询问,1<=T<=50000,1<=N, M<= ...

  4. POJ1511 Invitation Cards SPFA算法裸题变形

    原题目:http://poj.org/problem?id=1511 给出一个有向图,求出这个图从1到所有点的最短路径和所有点到1的最短路径的和. 这题数据量有点大,数据范围也大,所以用SPFA+邻接 ...

  5. HDU1253 胜利大逃亡 (BFS)

      胜利大逃亡 Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Sub ...

  6. MYSQL查询字段全部为中文的字段

    在实际使用mysql的过程中,会遇到这样的问题,查询字段内容全部为中文内容的数据,对于刚用mysql的小伙伴可能就比较迷失了,不知道怎么使用,其实这个问题很简单,使用下面这个sql语句就可以了 SEL ...

  7. join与os.path.join

    Python中有join和os.path.join()两个函数,具体作用如下: join:连接字符串数组.将字符串.元组.列表中的元素以指定的字符(分隔符)连接生成一个新的字符串os.path.joi ...

  8. iperf简单说明

    1.官网下载安装包 https://iperf.fr/iperf-download.php 2.安装(根据下载包的类型进行安装) 3.参数说明服务端(默认监听端口5201) iperf -s -u - ...

  9. codeforces-473D Mahmoud and Ehab and another array construction task (素数筛法+贪心)

    题目传送门 题目大意:先提供一个数组,让你造一个数组,这个数组的要求是 1 各元素之间都互质  2  字典序大于等于原数组  3 每一个元素都大于2 思路: 1.两个数互质的意思就是没有公因子.所以每 ...

  10. Life is a journey

    Life is a journey. What we should care about is not where it's headed but what we see and how we fee ...