在很多项目中, 需要用到缓存,借鉴网上前辈们的一些经验,自己再进行总结简化了一些, 做出如下的缓存操作,其中包含内存缓存(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 关于缓存的实现的更多相关文章

  1. Asp.Net Core 2.0 项目实战(8)Core下缓存操作、序列化操作、JSON操作等Helper集合类

    本文目录 1.  前沿 2.CacheHelper基于Microsoft.Extensions.Caching.Memory封装 3.XmlHelper快速操作xml文档 4.Serializatio ...

  2. 讨论过后而引发对EF 6.x和EF Core查询缓存的思考

    前言 最近将RabbitMQ正式封装引入到.NET Core 2.0项目当中,之前从未接触过是个高大上的东东跟着老大学习中,其中收获不少,本打算再看看RabbitMQ有时间写写,回来后和何镇汐大哥探讨 ...

  3. ASP.NET Core 开发-缓存(Caching)

    ASP.NET Core 缓存Caching,.NET Core 中为我们提供了Caching 的组件. 目前Caching 组件提供了三种存储方式. Memory Redis SqlServer 学 ...

  4. .NET Core 的缓存篇之MemoryCache

    前言 对于缓存我们都已经很熟悉了,缓存分为很多种,浏览器缓存.试图缓存.服务器缓存.数据库缓存等等一些,那今天我们先介绍一下视图缓存和MemoryCache内存缓存的概念和用法: 视图缓存 在老的版本 ...

  5. Asp.Net Core 轻松学-在.Net Core 使用缓存和配置依赖策略

    前言     几乎在所有的应用程序中,缓存都是一个永恒的话题,恰当的使用缓存可以有效提高应用程序的性能:在某些业务场景下,使用缓存依赖会有很好的体验:在 Asp.Net Core 中,支持了多种缓存组 ...

  6. .NET Core MemoryCache缓存获取全部缓存键

    在Core中不能使用原HttpRuntime.Cache缓存,改为MemoryCache(Microsoft.Extensions.Caching.Memory). 现MemoryCache新版为2. ...

  7. .net core响应缓存

    按照官网资料操作无效,这里使用https://github.com/speige/AspNetCore.ResponseCaching.Extensions的扩展包 安装AspNetCore.Resp ...

  8. net core WebApi——缓存神器Redis

    目录 前言 Redis 使用 RedisUtil 测试 小结 @ 前言 中秋过完不知不觉都已经快两周没动这个工程了,最近业务需要总算开始搞后台云服务了,果断直接net core搞起,在做的中间遇到了不 ...

  9. CacheManager Net Core Redis 缓存

    using CacheManager.Core; using System; using System.Collections.Generic; using System.Text; namespac ...

随机推荐

  1. 模式识别笔记4-集成学习之AdaBoost

    目前集成学习(Ensemble Learning) 分为两类: 个体学习器间存在强依赖关系.必须串行化生成的序列化方法:Boosting 个体学习器间不存在强依赖关系,可同时生成的并行化方法:Bagg ...

  2. 【朝花夕拾】四大组件之(一)Broadcast篇

    前言 笔者最近在探究ANR及源码的过程中,发现对Broadcast的一些应用层面上的知识有的感觉比较生疏,有的记忆不准确,有的认识不完整.所谓“基础不牢,地动山摇”,于是就梳理了一下Broadcast ...

  3. BaiduSpeechDemo【百度语音SDK集成】(基于v3.0.7.3)

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 本Demo将百度语音SDK(其中一部分功能)和自定义的UI对话框封装到一个module中,便于后续的SDK版本更新以及调用. 本De ...

  4. 用Python教你微信防撤回(文本、图片、语音、视频、名片等...)

    大家在使用微信过程中,有时候消息还没看到,就被撤回了.毕竟好奇心大家都有,明知到消息被撤回了,就更想去看一下是什么内容心里想着万一是女神给我表白了呢.. 今天就用Python来做个微信防撤回的小功能. ...

  5. 前端笔记之移动端&响应式(下)默认样式&事件&惯性抛掷&swiper&loaction对象

    一.移动端默认样式 ·IOS和Android下触摸元素时出现半透明灰色遮罩 a,input,button{ -webkit-tap-highlight-color: transparent; } ·I ...

  6. Nginx反向代理和Node.js后端解决跨域问题

    最近在写自己的博客,涉及到跨域的问题,自己捣鼓许久,终于解决了.然后总结一下,记录一下,日后遇到类似的问题的时候也可以得到一些启发. 一.什么是跨域 跨域,指的是浏览器不能执行其他网站的脚本.它是由浏 ...

  7. js获取url 中的值,并跳转相应页面

    实现方法:一:获取URL带QUESTRING参数的JAVASCRIPT客户端解决方案,相当于asp的request.querystring,PHP的$_GET1.函数: <Script lang ...

  8. MySQL优化面试

    原则:尽量使用整型表示字符串 存储IP INET_ATON(str),address to number INET_NTOA(number),number to address MySQL内部的枚举类 ...

  9. AngularJS实现的自定义过滤器简单示例

    本文实例讲述了AngularJS实现的自定义过滤器.分享给大家供大家参考,具体如下: 1.自定义限制字数的过滤器 啥也不说了直接上代码吧 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 ...

  10. 前端入门21-JavaScript的ES6新特性

    声明 本篇内容全部摘自阮一峰的:ECMAScript 6 入门 阮一峰的这本书,我个人觉得写得挺好的,不管是描述方面,还是例子,都讲得挺通俗易懂,每个新特性基本都还会跟 ES5 旧标准做比较,说明为什 ...