memoryCache的使用
1 借鉴这篇文章
https://www.cnblogs.com/zuowj/p/8440902.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Caching;
using System.Diagnostics; namespace ConsoleApp1
{
public static class MemoryCacheHelper
{
private static readonly object _locker = new object();
private static readonly object _locker2 = new object(); /// <summary>
/// 根据key取缓存,不存在则返回null
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T GetCacheItem<T>(String key)
{
try
{
return (T)MemoryCache.Default[key];
}
catch (Exception ex)
{ return default(T);
}
} /// <summary>
/// 是否包含指定键的缓存项
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Contains(string key)
{
return MemoryCache.Default.Contains(key);
} public static T GetOrAddCacheItem<T>(string key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("Invalid cache key");
}
if (cachePopulate == null)
{
throw new ArgumentException("cachePopulate");
}
if (slidingExpiration == null && absoluteExpiration == null)
{
throw new ArgumentException("Either a sliding expiration or absolute must be provided");
}
if (MemoryCache.Default[key] == null)
{
lock (_locker)
{
if (MemoryCache.Default[key] == null)
{
T cacheValue = cachePopulate();
if (!typeof(T).IsValueType && ((object)cacheValue) == null)
{
return cacheValue;
}
var item = new CacheItem(key, cacheValue);
var policy = CreatePolicy(slidingExpiration, absoluteExpiration);
MemoryCache.Default.Add(item, policy);
} }
} return (T)MemoryCache.Default[key];
} public static T GetOrAddCacheItem<T>(string key,Func<T> cachePopulate,string dependencyFilePath)
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("Invalid cache key");
}
if (cachePopulate == null)
{
throw new ArgumentException("cachePopulate");
} if (MemoryCache.Default[key]==null)
{
lock (_locker2)
{
if (MemoryCache.Default[key] == null)
{
T cacheValue = cachePopulate();
if (!typeof(T).IsValueType && ((object)cacheValue) == null)
{
return cacheValue;
}
var item = new CacheItem(key, cacheValue);
var policy = CreatePolicy(dependencyFilePath);
MemoryCache.Default.Add(item, policy);
}
}
} return (T)MemoryCache.Default[key];
} /// <summary>
/// 移除指定键的缓存项
/// </summary>
/// <param name="key"></param>
public static void RemoveCacheItem(string key)
{
try
{
MemoryCache.Default.Remove(key);
}
catch (Exception)
{ }
} private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
{
var policy = new CacheItemPolicy();
if (slidingExpiration.HasValue)
{
policy.SlidingExpiration = slidingExpiration.Value;
}
else if (absoluteExpiration.HasValue)
{
policy.AbsoluteExpiration = absoluteExpiration.Value;
} policy.Priority = CacheItemPriority.Default;
return policy;
} /// <summary>
/// 缓存文件
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
private static CacheItemPolicy CreatePolicy(string filepath)
{
var policy = new CacheItemPolicy();
policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string>() { filepath })); policy.Priority = CacheItemPriority.Default;
return policy;
}
}
}
memoryCache的使用的更多相关文章
- 【无私分享:ASP.NET CORE 项目实战(第十一章)】Asp.net Core 缓存 MemoryCache 和 Redis
目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitHub上下载了十几个源码参考, Memory 和 Redis 终于写出一个 ...
- 基于MemoryCache的缓存辅助类
背景: 1. 什么是MemoryCache? memoryCache就是用电脑内存做缓存处理 2.使用范围? 可用于不常变的数据,进行保存在内存中,提高处理效率 代码: /// <summary ...
- 从零开始,搭建博客系统MVC5+EF6搭建框架(3),添加Nlog日志、缓存机制(MemoryCache、RedisCache)、创建控制器父类BaseController
一.回顾系统进度以及本章概要 目前博客系统已经数据库创建.以及依赖注入Autofac集成,接下来就是日志和缓存集成,这里日志用的是Nlog,其实还有其他的日志框架如log4,这些博客园都有很多介绍,这 ...
- Android开源框架:Universal-Image-Loader解析(二)MemoryCache
- .NET 4.0 MemoryCache with SqlChangeMonitor
Summary There isn't a lot of documentation on the internet about how to use the SqlChangeMonitor wit ...
- 缓存管理Memorycache 的使用
前言:什么是memoryCache? 一种缓存管理技术,某些只读数据频繁操作数据库,会对系统的性能有很大的开销,所以我们使用缓存技术,当数据库内容更新,我们在更更新缓存的数据值.目前缓存讲技术的产 ...
- Asp.net Core 缓存 MemoryCache 和 Redis
Asp.net Core 缓存 MemoryCache 和 Redis 目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitH ...
- 在.NET项目中使用PostSharp,使用MemoryCache实现缓存的处理(转)
在之前一篇随笔<在.NET项目中使用PostSharp,实现AOP面向切面编程处理>介绍了PostSharp框架的使用,试用PostSharp能给我带来很多便利和优势,减少代码冗余,提高可 ...
- 在.NET项目中使用PostSharp,使用MemoryCache实现缓存的处理
在之前一篇随笔<在.NET项目中使用PostSharp,实现AOP面向切面编程处理>介绍了PostSharp框架的使用,试用PostSharp能给我带来很多便利和优势,减少代码冗余,提高可 ...
- .NET Core 2.0迁移技巧之MemoryCache问题修复
对于传统的.NET Framework项目而言,System.Runtime.Caching命名空间是常用的工具了,其中MemoryCache类则常被用于实现内存缓存. .NET Core 2.0暂时 ...
随机推荐
- JQuery中formSerialize()报错:对象不支持"formSerialize"属性或方法
formSerialize()是jQuery的表单插件中提供的方法. formSerialize()的核心方法是:$.param(data); Form表单经过formSerialize(),被序列化 ...
- 定时备份删除数据库sql
1.备份数据库 mkdir -p /home/mysql/mysql_bak/ vi mysql_bak.sh #!/bin/bash #Shell Command For Backup MySQL ...
- idea的一些常用快捷键
快捷键 1.进入实现方法的快捷键 Ctrl + Alt + B Ctrl + Alt + 鼠标点击 2.自动给方法添加注释的快捷键 输入/**,然后回车 3.删除一行 CTRL + Y / CTRL ...
- 关于python中的路径
如果在train.py中调用了1.py中的A方法,则A中的相对路径按照train.py来写!
- POJ Corn Fields 状态压缩DP基础题
题目链接:http://poj.org/problem?id=3254 题目大意(名称什么的可能不一样,不过表达的意思还是一样的): 种玉米 王小二从小学一年级到现在每次考试都是班级倒数第一名,他的爸 ...
- Warning: Hash history cannot PUSH the same path; a new entry will not be added to the history stack
现象 在用`mobx-react-router`的`this.props.history.push("/")`的时候,浏览器会提示 Warning: Hash history ca ...
- 龙六网络科技有限公司(Dragon six Network Technology Co., Ltd.)
龙六网络科技有限公司(Dragon six Network Technology Co., Ltd.)
- setInterval【计时器】
~function(){ const nextPushTime = $('#nextPushTime_promotion_push'); const prevTime = new Date('2017 ...
- cuda-convnet在Ubuntu12.04+CUDA5.5下的配置
deep learning近年来非常之火,尤其是在IMAGENET上的识别效果更是惊呆了小伙伴,其所用的Hinton的学生编写的cuda-convet代码早已公开,但是一直没有时间去仔细研究,最近趁着 ...
- Jenkins+maven+gitlab自动化部署之构建Java应用(五)
前面几篇文章介绍jenkins部署以及配置,接下来我们,就介绍下如何使用jenkins发布应用. 1)新建项目 jenkins首页,点击左上新建任务,出现下图,填写对应信息,然后点击确定: 2)项目参 ...