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 ...
随机推荐
- python接口自动化:python3.6中import Crypto.Hash报错的解决方案
一:问题 python3.6中算法加密引入包Crypto报错,即便安装了: pip install crypto pip install pycrypto pip install pycryptodo ...
- Python中的OS对路径的操作以及应用
目录处理 OS目录处理目录-->路径,文件夹 文件:html 1. 新建和删除一个目录import os #引入os目录from xx import xxos.mkdir("D:\\P ...
- 带事务管理的spring数据库动态切换
动态切换数据源理论知识 项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此:又例如:读写分离数据库配置的系统. 1.相信很多人都知道JDK代理,分静态代理和动态代理两种,同样的 ...
- pytorch的matmul怎么广播
1)如果是两个1维的,就向量内积:2)如果两个都是2维的,就矩阵相乘3)如果第一个是1维,第二个是2维:填充第一个使得能够和第二个参数相乘:如果第一个是2维,第二个是1维,就是矩阵和向量相乘:例: a ...
- javascript中ClassName属性的详解与实例
在javascritp中,我们可以通过style属性可以控制元素的样式,从而实现行为层通过DOM的style属性去干预显示层显示的目标,但是这种方法是不好的,而且为了实现通过DOM脚本设置的样式,你不 ...
- idea 错误: 找不到或无法加载主类 xxx.xxx.xxxxx
idea 错误: 找不到或无法加载主类 xxx.xxx.xxxxx JDK环境,maven项目还是ee还是web项目,是否都正常. 如果是用idea打开的话,在源码目录上点击右键,然后找到Mark d ...
- MR1和MR2的工作原理
MapReduce1 分为6个步骤: 1.作业的提交 1).客户端向jobtracker请求一个新的作业ID(通过JobTracker的getNewJobId()方法获取,见第2步 2).计算作业的输 ...
- 表视图为Group类型的注意问题
使用group类型的tableview时,第一个section距离navigationbar的距离很大,不符合这边的设计图. 使用 myTableView . sectionHeaderHeight ...
- 添加额外yun源
.yum install jq 发没有jq安装包,无法安装 .下载并安装EPEL [root@node2 coredns]# wget http://dl.fedoraproject.org/pub/ ...
- 【知乎】github,Empty reply from server?
http://www.zhihu.com/question/26717343 问:用hexo搭了个blog,之前一直正常,最近在deploy的时候无法连接到github了. fatal: unab ...