.NET 6 基于IDistributedCache实现Redis与MemoryCache的缓存帮助类
本文通过IDistributedCache的接口方法,实现Redis与MemoryCache统一帮助类。只需要在配置文件中简单的配置一下,就可以实现Redis与MemoryCache的切换。
IDistributedCache
IDistributedCache 方法:
| 方法 | 说明 |
|---|---|
| Get(String) | 获取具有给定键的值。 |
| GetAsync(String, CancellationToken) | 获取具有给定键的值。 |
| Refresh(String) | 基于缓存中某个值的键刷新该值,并重置其可调到期超时(如果有)。 |
| RefreshAsync(String, CancellationToken) | 基于缓存中某个值的键刷新该值,并重置其可调到期超时(如果有)。 |
| Remove(String) | 删除具有给定键的值。 |
| RemoveAsync(String, CancellationToken) | 删除具有给定键的值。 |
| Set(String, Byte[], DistributedCacheEntryOptions) | 设置具有给定键的值。 |
| SetAsync(String, Byte[], DistributedCacheEntryOptions, CancellationToken) | 设置具有给定键的值。 |
IDistributedCache 还提供了一些扩展方法,本文的帮助类就是通过扩展方法完成的。
IDistributedCache 扩展方法:
| 方法 | 说明 |
|---|---|
| GetString(IDistributedCache, String) | 使用指定的键从指定的缓存中获取字符串。 |
| GetStringAsync(IDistributedCache, String, CancellationToken) | 使用指定的键从指定的缓存异步获取字符串。 |
| Set(IDistributedCache, String, Byte[]) | 使用指定的键设置指定缓存中的字节序列。 |
| SetAsync(IDistributedCache, String, Byte[], CancellationToken) | 使用指定的键异步设置指定缓存中的字节序列。 |
| SetString(IDistributedCache, String, String) | 使用指定的键在指定的缓存中设置字符串。 |
| SetString(IDistributedCache, String, String, DistributedCacheEntryOptions) | 使用指定的键在指定的缓存中设置字符串。 |
| SetStringAsync(IDistributedCache, String, String, DistributedCacheEntryOptions, CancellationToken) | 使用指定的键在指定的缓存中异步设置字符串。 |
| SetStringAsync(IDistributedCache, String, String, CancellationToken) | 使用指定的键在指定的缓存中异步设置字符串。 |
ICache 接口
ICache接口提供了设置缓存、获取缓存、删除缓存和刷新缓存的接口方法。
namespace CacheHelper
{
public interface ICache
{
#region 设置缓存
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">值</param>
void SetCache(string key, object value);
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">值</param>
Task SetCacheAsync(string key, object value);
/// <summary>
/// 设置缓存
/// 注:默认过期类型为绝对过期
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">值</param>
/// <param name="timeout">过期时间间隔</param>
void SetCache(string key, object value, TimeSpan timeout);
/// <summary>
/// 设置缓存
/// 注:默认过期类型为绝对过期
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">值</param>
/// <param name="timeout">过期时间间隔</param>
Task SetCacheAsync(string key, object value, TimeSpan timeout);
/// <summary>
/// 设置缓存
/// 注:默认过期类型为绝对过期
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">值</param>
/// <param name="timeout">过期时间间隔</param>
/// <param name="expireType">过期类型</param>
void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType);
/// <summary>
/// 设置缓存
/// 注:默认过期类型为绝对过期
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">值</param>
/// <param name="timeout">过期时间间隔</param>
/// <param name="expireType">过期类型</param>
Task SetCacheAsync(string key, object value, TimeSpan timeout, ExpireType expireType);
#endregion
#region 获取缓存
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存Key</param>
string GetCache(string key);
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存Key</param>
Task<string> GetCacheAsync(string key);
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存Key</param>
T GetCache<T>(string key);
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存Key</param>
Task<T> GetCacheAsync<T>(string key);
#endregion
#region 删除缓存
/// <summary>
/// 清除缓存
/// </summary>
/// <param name="key">缓存Key</param>
void RemoveCache(string key);
/// <summary>
/// 清除缓存
/// </summary>
/// <param name="key">缓存Key</param>
Task RemoveCacheAsync(string key);
#endregion
#region 刷新缓存
/// <summary>
/// 刷新缓存
/// </summary>
/// <param name="key">缓存Key</param>
void RefreshCache(string key);
/// <summary>
/// 刷新缓存
/// </summary>
/// <param name="key">缓存Key</param>
Task RefreshCacheAsync(string key);
#endregion
}
}
ExpireType枚举
ExpireType枚举标识缓存的过期类型,分为绝对过期与相对过期两个类型。
绝对过期:即自创建一段时间后就过期
相对过期:即该键未被访问后一段时间后过期,若此键一直被访问则过期时间自动延长。
namespace CacheHelper
{
public enum ExpireType
{
/// <summary>
/// 绝对过期
/// 注:即自创建一段时间后就过期
/// </summary>
Absolute,
/// <summary>
/// 相对过期
/// 注:即该键未被访问后一段时间后过期,若此键一直被访问则过期时间自动延长
/// </summary>
Relative,
}
}
CacheType 枚举
是使用MemoryCache,还是Redis,MemoryCache不支持分布式,Redis支持分布式。
namespace CacheHelper
{
public enum CacheType
{
/// <summary>
/// 使用内存缓存(不支持分布式)
/// </summary>
Memory,
/// <summary>
/// 使用Redis缓存(支持分布式)
/// </summary>
Redis
}
}
CacheHelper 缓存帮助类
namespace CacheHelper
{
public class CacheHelper : ICache
{
readonly IDistributedCache _cache;
public CacheHelper(IDistributedCache cache)
{
_cache = cache;
}
protected string BuildKey(string idKey)
{
return $"Cache_{GetType().FullName}_{idKey}";
}
public void SetCache(string key, object value)
{
string cacheKey = BuildKey(key);
_cache.SetString(cacheKey, value.ToJson());
}
public async Task SetCacheAsync(string key, object value)
{
string cacheKey = BuildKey(key);
await _cache.SetStringAsync(cacheKey, value.ToJson());
}
public void SetCache(string key, object value, TimeSpan timeout)
{
string cacheKey = BuildKey(key);
_cache.SetString(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout)
});
}
public async Task SetCacheAsync(string key, object value, TimeSpan timeout)
{
string cacheKey = BuildKey(key);
await _cache.SetStringAsync(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout)
});
}
public void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType)
{
string cacheKey = BuildKey(key);
if (expireType == ExpireType.Absolute)
{
//这里没转换标准时间,Linux时区会有问题?
_cache.SetString(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout)
});
}
else
{
_cache.SetString(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = timeout
});
}
}
public async Task SetCacheAsync(string key, object value, TimeSpan timeout, ExpireType expireType)
{
string cacheKey = BuildKey(key);
if (expireType == ExpireType.Absolute)
{
//这里没转换标准时间,Linux时区会有问题?
await _cache.SetStringAsync(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout)
});
}
else
{
await _cache.SetStringAsync(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = timeout
});
}
}
public string GetCache(string idKey)
{
if (idKey.IsNullOrEmpty())
{
return null;
}
string cacheKey = BuildKey(idKey);
var cache = _cache.GetString(cacheKey);
return cache;
}
public async Task<string> GetCacheAsync(string key)
{
if (key.IsNullOrEmpty())
{
return null;
}
string cacheKey = BuildKey(key);
var cache = await _cache.GetStringAsync(cacheKey);
return cache;
}
public T GetCache<T>(string key)
{
var cache = GetCache(key);
if (!cache.IsNullOrEmpty())
{
return cache.ToObject<T>();
}
return default(T);
}
public async Task<T> GetCacheAsync<T>(string key)
{
var cache = await GetCacheAsync(key);
if (!string.IsNullOrEmpty(cache))
{
return cache.ToObject<T>();
}
return default(T);
}
public void RemoveCache(string key)
{
_cache.Remove(BuildKey(key));
}
public async Task RemoveCacheAsync(string key)
{
await _cache.RemoveAsync(BuildKey(key));
}
public void RefreshCache(string key)
{
_cache.Refresh(BuildKey(key));
}
public async Task RefreshCacheAsync(string key)
{
await _cache.RefreshAsync(BuildKey(key));
}
}
}
CacheHelper 中,自定义了一个string的扩展方法ToObject<T>()。ToObject<T>()扩展方法使用了 Newtonsoft.Json。
/// <summary>
/// 将Json字符串反序列化为对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="jsonStr">Json字符串</param>
/// <returns></returns>
public static T ToObject<T>(this string jsonStr)
{
return JsonConvert.DeserializeObject<T>(jsonStr);
}
CacheHelper 的使用方法
安装Redis依赖
Redis依赖我使用的是Caching.CSRedis,安装依赖:
PM> Install-Package Caching.CSRedis -Version 3.6.90
配置appsettings.json
在appsettings.json中,对缓存进行配置:
"Cache": {
"CacheType": "Memory", // "Memory OR Redis"
"RedisEndpoint": "127.0.0.1:6379" //Redis节点地址,定义详见 https://github.com/2881099/csredis
},
如果要使用MemoryCache,CacheType就设置为Memory,如果要使用Redis,CacheType就设置为Redis。如果设置为Redis的话,还需要配置RedisEndpoint,保证Redis节点可用。
CacheOptions配置
编写一个名为CacheOptions的类。用于获取配置文件的配置节内容
namespace CacheHelper
{
public class CacheOptions
{
public CacheType CacheType { get; set; }
public string RedisEndpoint { get; set; }
}
}
IHostBuilder扩展方法UseCache
编写一个IHostBuilder的扩展方法UseCache,用于注入MemoryCache或是Redis
public static IHostBuilder UseCache(this IHostBuilder hostBuilder)
{
hostBuilder.ConfigureServices((buidlerContext, services) =>
{
var cacheOption = buidlerContext.Configuration.GetSection("Cache").Get<CacheOptions>();
switch (cacheOption.CacheType)
{
case CacheType.Memory: services.AddDistributedMemoryCache(); break;
case CacheType.Redis:
{
var csredis = new CSRedisClient(cacheOption.RedisEndpoint);
RedisHelper.Initialization(csredis);
services.AddSingleton(csredis);
services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
}; break;
default: throw new Exception("缓存类型无效");
}
});
return hostBuilder;
}
Program.cs中引用
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseCache();
CacheHelper的使用。
public class HomeController
{
readonly ICache _cache;
public HomeController
(
ICache cache,
)
{
_cache = cache;
}
public async Task CacheTest(string key)
{
string cache_value = "hello cache";
//同步方法
_cache.SetCache(key,cache_value );
string v = _cache.GetCache<string>(key);
_cache.RemoveCache(key);
//异步方法
await _cache.SetCacheAsync(key,cache_value );
string val = await _cache.GetCacheAsync<string>(key);
await _cache.RemoveCacheAsync(key);
}
}
总结
暂无,下次再会!
.NET 6 基于IDistributedCache实现Redis与MemoryCache的缓存帮助类的更多相关文章
- 基于Asp.net Core 3.1实现的Redis及MemoryCache缓存助手CacheHelper
这几天在面试,这个关于Redis缓存的博客一直没空写,今天总算有点时间了. 从很久很久之前,我就一直想学Redis了,反正看到各大招聘网上都要求Redis,不学就太落后了. 一开始我是按微软官网文档那 ...
- [Intel Edison开发板] 04、Edison开发基于nodejs和redis的服务器搭建
一.前言 intel-iot-examples-datastore 是Intel提供用于所有Edison开发板联网存储DEMO所需要的服务器工程.该工程是基于nodejs和redis写成的一个简单的工 ...
- 基于MemoryCache的缓存辅助类
背景: 1. 什么是MemoryCache? memoryCache就是用电脑内存做缓存处理 2.使用范围? 可用于不常变的数据,进行保存在内存中,提高处理效率 代码: /// <summary ...
- 基于Twemproxy的Redis集群搭建以及想法
基于Twemproxy的Redis集群方案(转) redis3.0 已经发布了几个月了,但是我这等菜鸟到网上还是没有找到很好的关于搭建redis3.0集群的文章,而且好像很多公司的redis版本还保持 ...
- 基于 php-redis 的redis操作
基于 php-redis 的redis操作 林涛 发表于:2016-5-13 12:12 分类:PHP 标签:php,php-redis,redis 203次 redis的操作很多的,下面的例子都是基 ...
- 基于nginx+lua+redis高性能api应用实践
基于nginx+lua+redis高性能api应用实践 前言 比较传统的服务端程序(PHP.FAST CGI等),大多都是通过每产生一个请求,都会有一个进程与之相对应,请求处理完毕后相关进程自动释放. ...
- 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; usi ...
- Python 基于python操纵redis入门介绍
基于python操纵redis入门介绍 by:授客 QQ:1033553122 测试环境 redis-3.0.7 CentOS 6.5-x86_64 python 3.3.2 基于Python操作R ...
- 基于Docker的redis集群搭建
Redis集群官方介绍:http://www.redis.cn/topics/cluster-tutorial.html 基于Docker搭建Redis集群 环境:6个节点,三主三从 制作Redis镜 ...
- 基于Redis的Spring cache 缓存介绍
目录 Cache API及默认提供的实现 demo 依赖包安装 定义实体类.服务类和相关配置文件 Cache注解 启用Cache注解 @CachePut @CacheEvict @Cacheable ...
随机推荐
- Kubernetes里的Service是如何工作的
Service是Kubernetes接入层的一种抽象资源,它为我们提供了一种固定的.统一的访问接口地址和负载均衡能力,这时可能会想到,当时使用docker-compose的时候,不存在Service概 ...
- MinIO Server配置指南
MinIO server在默认情况下会将所有配置信息存到 ${HOME}/.minio/config.json 文件中. 以下部分提供每个字段的详细说明以及如何自定义它们. 配置目录 默认的配置目录是 ...
- Elasticsearch删除操作详解
文章转载自: https://mp.weixin.qq.com/s?__biz=MzI2NDY1MTA3OQ==&mid=2247484022&idx=1&sn=7a4de21 ...
- 3_MyBatis
一. 引言 1.1 什么是框架? 软件的半成品, 解决了软件开发过程中的普适性问题, 从而简化了开发步骤, 提升了开发效率 1.2 什么是ORM框架? ORM(Object Relational Ma ...
- 报时机器人的rasa shell执行流程分析
本文以报时机器人为载体,介绍了报时机器人的对话能力范围.配置文件功能和训练和运行命令,重点介绍了rasa shell命令启动后的程序执行过程. 一.报时机器人项目结构 1.对话能力范围 (1)能够 ...
- 如何在linux下检测(自身)IP冲突
最近遇到一个需求,或者说是一个用户现场问题. 我们设备先安装,设置dhcp模式获取ip进行联网,后来又安装了其他设备,但该设备是手动设置的静态ip地址,正好与我们设备冲突,造成网络故障. 那我们就需要 ...
- PAT (Basic Level) Practice 1023 组个最小数 分数 20
给定数字 0-9 各若干个.你可以以任意顺序排列这些数字,但必须全部使用.目标是使得最后得到的数尽可能小(注意 0 不能做首位).例如:给定两个 0,两个 1,三个 5,一个 8,我们得到的最小的数就 ...
- MatrixOne从入门到实践01——初识MatrixOne
初识MatrixOne 简介 MatrixOrigin 矩阵起源 是一家数据智能领域的创新企业,其愿景是成为数字世界的核心技术提供者. 物理世界的数字化和智能化无处不在.我们致力于建设开放的技术开源社 ...
- Docker | 制作tomcat镜像并部署项目
本文讲解如何制作自己的tomcat镜像,并使用tomcat部署项目 原料准备: tomcat.jdk安装包,dockerfile文件 步骤 1.准备压缩包 jdk-8u301-linux-x64.ta ...
- Hive之安装
Hive安装 1. 依赖hadoop(另有hadoop安装文档) 执行程序运行在yarn上面,需要启动start-yarn.sh 2. 先安装MySQL MySQL安装详见数据库MySQL之安装:ht ...