ASP.NET CORE CACHE的使用(含MemoryCache,Redis)
原文:ASP.NET CORE CACHE的使用(含MemoryCache,Redis)
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
依赖命名空间:
Microsoft.AspNetCore.Mvc;//测试调用时
Microsoft.Extensions.Caching.Memory;
Microsoft.Extensions.Caching.Redis;
StackExchange.Redis;
Newtonsoft.Json;
定义通用工具类 :CacheUntity
public class CacheUntity
{
private static ICacheHelper _cache = new RedisCacheHelper();//默认使用Redis
private static bool isInited = false;
public static void Init(ICacheHelper cache)
{
if (isInited)
return;
_cache.Dispose();
_cache = cache;
isInited = true;
}
public static bool Exists(string key)
{
return _cache.Exists(key);
}
public static T GetCache<T>(string key) where T : class
{
return _cache.GetCache<T>(key);
}
public static void SetCache(string key, object value)
{
_cache.SetCache(key, value);
}
public static void SetCache(string key, object value, DateTimeOffset expiressAbsoulte)
{
_cache.SetCache(key, value, expiressAbsoulte);
}
//public void SetCache(string key, object value, double expirationMinute)
//{
//}
public static void RemoveCache(string key)
{
_cache.RemoveCache(key);
}
}
定义统一缓存操作接口:ICacheHelper
public interface ICacheHelper
{
bool Exists(string key);
T GetCache<T>(string key) where T : class;
void SetCache(string key, object value);
void SetCache(string key, object value, DateTimeOffset expiressAbsoulte);//设置绝对时间过期
//void SetCache(string key, object value, double expirationMinute); //设置滑动过期, 因redis暂未找到自带的滑动过期类的API,暂无需实现该接口
void RemoveCache(string key);
void Dispose();
}
定义RedisCache帮助类:RedisCacheHelper
public class RedisCacheHelper : ICacheHelper
{
public RedisCacheHelper(/*RedisCacheOptions options, int database = 0*/)//这里可以做成依赖注入,但没打算做成通用类库,所以直接把连接信息直接写在帮助类里
{
RedisCacheOptions options = new RedisCacheOptions();
options.Configuration = "127.0.0.1:6379";
options.InstanceName = "test";
int database = 0;
_connection = ConnectionMultiplexer.Connect(options.Configuration);
_cache = _connection.GetDatabase(database);
_instanceName = options.InstanceName;
}
private IDatabase _cache;
private ConnectionMultiplexer _connection;
private readonly string _instanceName;
private string GetKeyForRedis(string key)
{
return _instanceName + key;
}
public bool Exists(string key)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
return _cache.KeyExists(GetKeyForRedis(key));
}
public T GetCache<T>(string key) where T : class
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
var value = _cache.StringGet(GetKeyForRedis(key));
if (!value.HasValue)
return default(T);
return JsonConvert.DeserializeObject<T>(value);
}
public void SetCache(string key, object value)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (Exists(GetKeyForRedis(key)))
RemoveCache(GetKeyForRedis(key));
_cache.StringSet(GetKeyForRedis(key), JsonConvert.SerializeObject(value));
}
public void SetCache(string key, object value, DateTimeOffset expiressAbsoulte)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (Exists(GetKeyForRedis(key)))
RemoveCache(GetKeyForRedis(key));
_cache.StringSet(GetKeyForRedis(key), JsonConvert.SerializeObject(value), expiressAbsoulte - DateTime.Now);
}
//public void SetCache(string key, object value, double expirationMinute)
//{
// if (Exists(GetKeyForRedis(key)))
// RemoveCache(GetKeyForRedis(key));
// DateTime now = DateTime.Now;
// TimeSpan ts = now.AddMinutes(expirationMinute) - now;
// _cache.StringSet(GetKeyForRedis(key), JsonConvert.SerializeObject(value), ts);
//}
public void RemoveCache(string key)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
_cache.KeyDelete(GetKeyForRedis(key));
}
public void Dispose()
{
if (_connection != null)
_connection.Dispose();
GC.SuppressFinalize(this);
}
}
定义MemoryCache帮助类:MemoryCacheHelper
public class MemoryCacheHelper : ICacheHelper
{
public MemoryCacheHelper(/*MemoryCacheOptions options*/)//这里可以做成依赖注入,但没打算做成通用类库,所以直接把选项直接封在帮助类里边
{
//this._cache = new MemoryCache(options);
this._cache = new MemoryCache(new MemoryCacheOptions());
}
private IMemoryCache _cache;
public bool Exists(string key)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
object v = null;
return this._cache.TryGetValue<object>(key, out v);
}
public T GetCache<T>(string key) where T : class
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
T v = null;
this._cache.TryGetValue<T>(key, out v);
return v;
}
public void SetCache(string key, object value)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
object v = null;
if (this._cache.TryGetValue(key, out v))
this._cache.Remove(key);
this._cache.Set<object>(key, value);
}
public void SetCache(string key, object value, double expirationMinute)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
object v = null;
if (this._cache.TryGetValue(key, out v))
this._cache.Remove(key);
DateTime now = DateTime.Now;
TimeSpan ts = now.AddMinutes(expirationMinute) - now;
this._cache.Set<object>(key, value, ts);
}
public void SetCache(string key, object value, DateTimeOffset expirationTime)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
object v = null;
if (this._cache.TryGetValue(key, out v))
this._cache.Remove(key);
this._cache.Set<object>(key, value, expirationTime);
}
public void RemoveCache(string key)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
this._cache.Remove(key);
}
public void Dispose()
{
if (_cache != null)
_cache.Dispose();
GC.SuppressFinalize(this);
}
}
调用:
[HttpGet]
public string TestCache()
{
CacheUntity.SetCache("test", "RedisCache works!");
string res = CacheUntity.GetCache<string>("test");
res += Environment.NewLine;
CacheUntity.Init(new MemoryCacheHelper());
CacheUntity.SetCache("test", "MemoryCache works!");
res += CacheUntity.GetCache<string>("test");
return res;
}
ASP.NET CORE CACHE的使用(含MemoryCache,Redis)的更多相关文章
- 在ASP.NET Core 2.0中使用MemoryCache
说到内存缓存大家可能立马想到了HttpRuntime.Cache,它位于System.Web命名空间下,但是在ASP.NET Core中System.Web已经不复存在.今儿个就简单的聊聊如何在ASP ...
- 第十二节:Asp.Net Core 之分布式缓存(SQLServer和Redis)
一. 整体说明 1. 说明 分布式缓存通常是指在多个应用程序服务器的架构下,作为他们共享的外部服务共享缓存,常用的有SQLServer.Redis.NCache. 特别说明一下:这里的分布式是 ...
- asp.net core计划任务探索之hangfire+redis+cluster
研究了一整天的quartz.net,发现一直无法解决cluster模式下多个node独立运行的问题,改了很多配置项,仍然是每个node各自为战.本来cluster模式下的各个node应该是负载均衡的, ...
- 记一次使用Asp.Net Core WebApi 5.0+Dapper+Mysql+Redis+Docker的开发过程
#前言 我可能有三年没怎么碰C#了,目前的工作是在全职搞前端,最近有时间抽空看了一下Asp.net Core,Core版本号都到了5.0了,也越来越好用了,下面将记录一下这几天以来使用Asp.Net ...
- ASP.NET Core中的缓存[1]:如何在一个ASP.NET Core应用中使用缓存
.NET Core针对缓存提供了很好的支持 ,我们不仅可以选择将数据缓存在应用进程自身的内存中,还可以采用分布式的形式将缓存数据存储在一个“中心数据库”中.对于分布式缓存,.NET Core提供了针对 ...
- asp.net core 系列之Response caching(1)
这篇文章简单的讲解了response caching: 讲解了cache-control,及对其中的头和值的作用,及设置来控制response caching; 简单的罗列了其他的缓存技术:In-me ...
- 从零搭建一个IdentityServer——集成Asp.net core Identity
前面的文章使用Asp.net core 5.0以及IdentityServer4搭建了一个基础的验证服务器,并实现了基于客户端证书的Oauth2.0授权流程,以及通过access token访问被保护 ...
- asp.net core 实战之 redis 负载均衡和"高可用"实现
1.概述 分布式系统缓存已经变得不可或缺,本文主要阐述如何实现redis主从复制集群的负载均衡,以及 redis的"高可用"实现, 呵呵双引号的"高可用"并不是 ...
- 简易的开发框架(微服务) Asp.Net Core 2.0
Asp.Net Core 2.0 + Mysql Orm + Ioc + Redis + AOP + RabbitMQ + Etcd + Autofac + Swagger 基础框架: https ...
随机推荐
- 成员函数定义后面加 const 的意义
我们定义的类的成员函数中,常常有一些成员函数不改变类的数据成员,也就是说,这些函数是"只读"函数,而有一些函数要修改类数据成员的值.如果把不改变数据成员的函数都加上const关键字 ...
- <context:component-scan>标签报错解决方案
- 在.slurm文件中激活Anaconda环境
超算中心使用slurm作为集群调度.原始slurm脚本如下: source activate tensorflow-gpu python neural_style.py --content conte ...
- 纹身女孩 Tattooed girl 可爱动人 出水芙蓉 窈窕多姿
目录 开宗明义
- mysql timestamp为0值时,python读取后的对象为None
MySQL数据表中,如果timestamp类型的字段,值为0, python从数据库读取数据后,得到对象是什么类型,是否为None呢? 下面来测试下. 创建数据表 首先创建数据表,其中字段pr_rul ...
- layui时间控件选择时间范围
layui.use([ 'laydate'], function(){ var $ = layui.$; var laydate = layui.laydate; var max = ${nowYea ...
- iOS上传图片问题
今天一定得写一篇博客,有以下原因: 1>第一次做图片上传的功能,算是一种记录吧; 2>在这个问题上,纠结,迷茫了很久,主要还是被后台坑了; 1.上传图片的方法是用的AFNetWorking ...
- .net core中读取配置文件
1)先看丑陋的方法 读取 appsettings.json 然后在 Startup 的 ConfigureServices() 方法中进行注入: public IConfigurationRoot ...
- 自定义 filter simple_tag inclusion_tag 总结
在已经注册的app下创建templatetags的python包 在包内创建py文件 my_tags.py 在py文件中写代码: from django import template registe ...
- 【Python开发】PyQt5应用与实践
一个典型的GUI应用程序可以抽象为:主界面(菜单栏.工具栏.状态栏.内容区域),二级界面(模态.非模态),信息提示(Tooltip),程序图标等组成.本篇根据作者使用PyQt5编写的一个工具,介绍如何 ...