Net core 关于缓存的实现
在很多项目中, 需要用到缓存,借鉴网上前辈们的一些经验,自己再进行总结简化了一些, 做出如下的缓存操作,其中包含内存缓存(IMemoryCache) 和 Redis 缓存;
一.前提内容, 导入两个包: Microsoft.Extensions.Caching.Memory 和 Microsoft.Extensions.Caching.Redis ,并在使用的类中using 一下它们. 我这里是用2.1.0版本的;
二. 创建 ICacheService 公共接口 ,我这里写的比较简单, 如若业务需要可自行增加 异步和批量的接口方法.
/// <summary>
/// 缓存接口
/// 分别内存缓存和Redis缓存(2.1.0版本)
/// </summary>
public interface ICacheService
{
/// <summary>
/// 新增
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="ExpirtionTime"></param>
/// <returns></returns>
bool Add(string key, object value, int ExpirtionTime = ); /// <summary>
/// 获取
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
string GetValue(string key);
/// <summary>
/// 验证缓存项是否存在
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
bool Exists(string key); /// <summary>
/// 移除
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
bool Remove(string key);
}
三. 再分别创建 MemoryCacheService 和RedisCacheService 类, 并继承 ICacheService 接口.
a. MemoryCacheService 类 , 记得using 一下 Microsoft.Extensions.Caching.Memory
/// <summary>
/// 缓存接口实现
/// </summary>
public class MemoryCacheService : ICacheService
{
protected IMemoryCache _cache; public MemoryCacheService(IMemoryCache cache)
{
_cache = cache;
} public bool Add(string key, object value, int ExpirtionTime = )
{
if (!string.IsNullOrEmpty(key))
{
_cache.Set(key, value , DateTimeOffset.Now.AddMinutes(ExpirtionTime));
}
return true;
} public bool Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
}
if (Exists(key))
{
_cache.Remove(key);
return true;
}
return false;
} public string GetValue(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
if (Exists(key))
{
return _cache.Get(key).ToString();
}
return null;
} public bool Exists(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
} object cache;
return _cache.TryGetValue(key, out cache);
} }
b. RedisCacheService 类 , 记得using 一下 Microsoft.Extensions.Caching.Redis
public class RedisCacheService:ICacheService
{
protected RedisCache _redisCache = null; public RedisCacheService(RedisCacheOptions options)
{
_redisCache = new RedisCache(options);
} public bool Add(string key, object value,int ExpirtionTime=)
{
if (!string.IsNullOrEmpty(key))
{
_redisCache.Set(key, Encoding.UTF8.GetBytes(value.ToString()), new DistributedCacheEntryOptions()
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(ExpirtionTime)
});
}
return true;
} public bool Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
} if (Exists(key))
{
_redisCache.Remove(key);
return true;
}
return false;
} public string GetValue(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
if (Exists(key))
{
return _redisCache.GetString(key);
}
return null;
} public bool Exists(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
}
return !string.IsNullOrEmpty(_redisCache.GetString(key)) ? true :false;
} }
四. 在 Startup.cs 文件中注入 Redis 和Memory. 这里啰嗦多几句, 因为同一个接口注入了多个实现, 那到调用的时候, 容器是怎么知道调用哪个类呢? 我这里是参考了
ASP.NET Core默认注入方式下如何注入多个实现(多种方式) ,
services.AddTransient<MemoryCacheService>(); //内存缓存认证注入
//注入Redis
services.AddSingleton(new RedisCacheService(new RedisCacheOptions()
{
InstanceName = Configuration.GetSection("Redis:InstanceName").Value,
Configuration= Configuration.GetSection("Redis:Connection").Value
}));
并在appsettings.json配置redis ,
"Redis": {
"Connection": "127.0.0.1:6379",
"InstanceName": "Redis:"
}
服务调用我使用了IServiceProvider .
调用如下:

五.总结
总算是写了一篇让自己看得懂一些的文章了. 行吧...算是一个小进步吧!
Net core 关于缓存的实现的更多相关文章
- Asp.Net Core 2.0 项目实战(8)Core下缓存操作、序列化操作、JSON操作等Helper集合类
本文目录 1. 前沿 2.CacheHelper基于Microsoft.Extensions.Caching.Memory封装 3.XmlHelper快速操作xml文档 4.Serializatio ...
- 讨论过后而引发对EF 6.x和EF Core查询缓存的思考
前言 最近将RabbitMQ正式封装引入到.NET Core 2.0项目当中,之前从未接触过是个高大上的东东跟着老大学习中,其中收获不少,本打算再看看RabbitMQ有时间写写,回来后和何镇汐大哥探讨 ...
- ASP.NET Core 开发-缓存(Caching)
ASP.NET Core 缓存Caching,.NET Core 中为我们提供了Caching 的组件. 目前Caching 组件提供了三种存储方式. Memory Redis SqlServer 学 ...
- .NET Core 的缓存篇之MemoryCache
前言 对于缓存我们都已经很熟悉了,缓存分为很多种,浏览器缓存.试图缓存.服务器缓存.数据库缓存等等一些,那今天我们先介绍一下视图缓存和MemoryCache内存缓存的概念和用法: 视图缓存 在老的版本 ...
- Asp.Net Core 轻松学-在.Net Core 使用缓存和配置依赖策略
前言 几乎在所有的应用程序中,缓存都是一个永恒的话题,恰当的使用缓存可以有效提高应用程序的性能:在某些业务场景下,使用缓存依赖会有很好的体验:在 Asp.Net Core 中,支持了多种缓存组 ...
- .NET Core MemoryCache缓存获取全部缓存键
在Core中不能使用原HttpRuntime.Cache缓存,改为MemoryCache(Microsoft.Extensions.Caching.Memory). 现MemoryCache新版为2. ...
- .net core响应缓存
按照官网资料操作无效,这里使用https://github.com/speige/AspNetCore.ResponseCaching.Extensions的扩展包 安装AspNetCore.Resp ...
- net core WebApi——缓存神器Redis
目录 前言 Redis 使用 RedisUtil 测试 小结 @ 前言 中秋过完不知不觉都已经快两周没动这个工程了,最近业务需要总算开始搞后台云服务了,果断直接net core搞起,在做的中间遇到了不 ...
- CacheManager Net Core Redis 缓存
using CacheManager.Core; using System; using System.Collections.Generic; using System.Text; namespac ...
随机推荐
- Vue(day4)
这里说的Vue中的路由是指前端路由,与后端路由有所区别.我们可以使用url来获取服务器的资源,而这种url与资源的映射关系就是我们所说的路由.对于单页面程序来说,我们使用url时常常通过hash的方法 ...
- ViewPagerWithImageDemo【ViewPager如何判断滑动到第一页和最后一页以及弹出对话框功能】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 记录viewpager滑动的时候弹出对话框的功能(关键功能是滑动弹出对话框后,隐藏对话框的时候当前页可以还原到原位置),顺便判断首页 ...
- [翻译]Linux 内核里的数据结构 —— 基数树
目录 Linux 内核里的数据结构 -- 基数树 基数树 Radix tree Linux内核基数树API 链接 Linux 内核里的数据结构 -- 基数树 基数树 Radix tree 正如你所知道 ...
- SLAM+语音机器人DIY系列:(二)ROS入门——5.编写简单的消息发布器和订阅器
摘要 ROS机器人操作系统在机器人应用领域很流行,依托代码开源和模块间协作等特性,给机器人开发者带来了很大的方便.我们的机器人“miiboo”中的大部分程序也采用ROS进行开发,所以本文就重点对ROS ...
- [Vue] vuex进行组件间通讯
vue 组件之间数据传输(vuex) 初始化 store src/main.js import Vuex from "vuex"; Vue.use(Vuex); new Vue({ ...
- 制作联动时,数据绑定combox控件会触发SelectedIndexChanged事件
看过很多个网站的解决办法,基本雷同,还不能解决,真怀疑他们是互相直接炒的,没事通过验证. 在做省市区的三级联动时候出现这个问题,最后通过先设置值对象和显示对象,最后才绑定数据,这样一个逻辑操作,什么问 ...
- 将Xml文件递归加载到TreeView中
#region [通过XDocument的方式将Xml文件递归到TreeView控件中] //读取Xml文件(XDocument) //1.加载Xml文件 XDocument document=XD ...
- IOC之Unity的使用详解
原文链接:https://www.cnblogs.com/hua66/p/9670639.html Unity作为Microsoft推出IOC容器,其功能是非常丰富的,其中需要注意的地方也不少.以下是 ...
- 0423上课练习(list、while、def)
""" 循环录入3个正整数,求最大值,最小值,总和,平均值 访问列表中的元素: 列表的长度: len(列表名) 索引值的范围:[0,len(列表名)-1] 列表名[索引值 ...
- 如何利用GitHub设计一个炫酷的个人网站(含代码)
1.在开始制作之前我们先预览一下我的网站吧! 1.方式一: 由于是手机版的所以用手机访问下面的链接体验比较好一点: https://tom-shushu.github.io/MyWeb.github. ...