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. 自定义Mybatis框架

    项目结构:      https://files-cdn.cnblogs.com/files/mkl7/ownMybatis.zip 1. 创建maven工程并引入坐标: <?xml versi ...

  2. npm 还是 yarn ?

    技术选型时这个问题总是困扰我,今天看到一篇文章,详细的解释了 npm 和 yarn 在性能,安全,支持性和使用难易度上的区别,看完之后这个问题终于有一个答案: 如果你在意速度和 UI,选 yarn,如 ...

  3. MongoDB入门,安装配置与基本CURD操作

    MongoDB特点 MongoDB是NoSQL的一种,非关系型数据库,或者叫不只是关系型数据库(Not Only SQL).MongoDB采用json格式的文档存储,与Redis的key-value有 ...

  4. MySQL之常用命令

    前言 在说MySQL命令之前,需要介绍一些navicat:navicat是一套快速.可靠并且价格相宜的数据库管理工具,它的出现简化了数据库的管理,降低了管理成本,提高了对数据库的管理效率.Navica ...

  5. VB-机房收费系统之Excel导出

    敲机房很久了,感觉对代码的感知力终于有所提高了,很是开心.今天在敲学生充值记录查询的时候发现,其中有了新的知识,  这时候就该到了分析问题的时候了.不说废话了! 首先 保证自己的笔记本或者电脑上必须有 ...

  6. Cardinality (基数)

    名词 Cardinality:    优化器在计算成本的时候,需要从统计信息中取得数据,然后去估计每一步操作所涉及的行数,叫做Cardinality.    比如,一张表T有1000行数据,列COL1 ...

  7. 1、OpenCV Python 图像加载和保存

    __author__ = "WSX" import cv2 as cv # 这里的文件是图片或者视频 def Save_File( image ): cv.imwrite(&quo ...

  8. Flume启动时报错Caused by: java.lang.InterruptedException: Timed out before HDFS call was made. Your hdfs.callTimeout might be set too low or HDFS calls are taking too long.解决办法(图文详解)

    前期博客 Flume自定义拦截器(Interceptors)或自带拦截器时的一些经验技巧总结(图文详解) 问题详情 -- ::, (agent-shutdown-hook) [INFO - org.a ...

  9. 百度地图 js 调用

    百度地图key 的获取 进入 http://lbsyun.baidu.com/i 登录你的账号 点击进入控制台,复制 ak 的值 <!doctype html> <html> ...

  10. 爬取猫眼电影top100的代码

    废话不说,代码附上: #encoding:utf-8 import requests import re import json from multiprocessing import Pool #多 ...