.NET 6 基于IDistributedCache实现Redis与MemoryCache的缓存帮助类
admin
2024-03-03 01:31:22
0

本文通过IDistributedCache的接口方法,实现RedisMemoryCache统一帮助类。只需要在配置文件中简单的配置一下,就可以实现Redis与MemoryCache的切换。

目录

  • IDistributedCache
    • IDistributedCache 方法:
    • IDistributedCache 扩展方法:
  • ICache 接口
  • ExpireType枚举
  • CacheType 枚举
  • CacheHelper 缓存帮助类
  • CacheHelper 的使用方法
    • 安装Redis依赖
    • 配置appsettings.json
    • CacheOptions配置
    • IHostBuilder扩展方法UseCache
    • Program.cs中引用
  • CacheHelper的使用。
  • 总结

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 设置缓存 /// /// 设置缓存/// /// 缓存Key/// 值void SetCache(string key, object value);/// /// 设置缓存/// /// 缓存Key/// 值Task SetCacheAsync(string key, object value);/// /// 设置缓存/// 注:默认过期类型为绝对过期/// /// 缓存Key/// 值/// 过期时间间隔void SetCache(string key, object value, TimeSpan timeout);/// /// 设置缓存/// 注:默认过期类型为绝对过期/// /// 缓存Key/// 值/// 过期时间间隔Task SetCacheAsync(string key, object value, TimeSpan timeout);/// /// 设置缓存/// 注:默认过期类型为绝对过期/// /// 缓存Key/// 值/// 过期时间间隔/// 过期类型  void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType);/// /// 设置缓存/// 注:默认过期类型为绝对过期/// /// 缓存Key/// 值/// 过期时间间隔/// 过期类型  Task SetCacheAsync(string key, object value, TimeSpan timeout, ExpireType expireType);#endregion#region 获取缓存/// /// 获取缓存/// /// 缓存Keystring GetCache(string key);/// /// 获取缓存/// /// 缓存KeyTask GetCacheAsync(string key);/// /// 获取缓存/// /// 缓存KeyT GetCache(string key);/// /// 获取缓存/// /// 缓存KeyTask GetCacheAsync(string key);#endregion#region 删除缓存/// /// 清除缓存/// /// 缓存Keyvoid RemoveCache(string key);/// /// 清除缓存/// /// 缓存KeyTask RemoveCacheAsync(string key);#endregion#region 刷新缓存/// /// 刷新缓存/// /// 缓存Keyvoid RefreshCache(string key);/// /// 刷新缓存/// /// 缓存KeyTask RefreshCacheAsync(string key);#endregion}
}

ExpireType枚举

ExpireType枚举标识缓存的过期类型,分为绝对过期相对过期两个类型。
绝对过期:即自创建一段时间后就过期
相对过期:即该键未被访问后一段时间后过期,若此键一直被访问则过期时间自动延长。

namespace CacheHelper
{public enum ExpireType{/// /// 绝对过期/// 注:即自创建一段时间后就过期/// Absolute,/// /// 相对过期/// 注:即该键未被访问后一段时间后过期,若此键一直被访问则过期时间自动延长/// Relative,}
}

CacheType 枚举

是使用MemoryCache,还是RedisMemoryCache不支持分布式,Redis支持分布式。

namespace CacheHelper
{public enum CacheType{/// /// 使用内存缓存(不支持分布式)/// Memory,/// /// 使用Redis缓存(支持分布式)/// 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 GetCacheAsync(string key){if (key.IsNullOrEmpty()){return null;}string cacheKey = BuildKey(key);var cache = await _cache.GetStringAsync(cacheKey);return cache;}public T GetCache(string key){var cache = GetCache(key);if (!cache.IsNullOrEmpty()){return cache.ToObject();}return default(T);}public async Task GetCacheAsync(string key){var cache = await GetCacheAsync(key);if (!string.IsNullOrEmpty(cache)){return cache.ToObject();}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()ToObject()扩展方法使用了 Newtonsoft.Json

/// 
/// 将Json字符串反序列化为对象
/// 
/// 对象类型
/// Json字符串
/// 
public static T ToObject(this string jsonStr)
{return JsonConvert.DeserializeObject(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();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(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(key);_cache.RemoveCache(key);//异步方法await _cache.SetCacheAsync(key,cache_value );string val = await _cache.GetCacheAsync(key);await _cache.RemoveCacheAsync(key);}
}

总结

暂无,下次再会

相关内容

热门资讯

跨境电商巨无霸,赴港IPO获证... 来源:上海证券报 7月10日,中国证监会国际合作司发布关于SHEIN Global Holdings...
陪爸妈走过的第四个城市 陪爸妈走过的第四个城市 开篇 今年春天,趁着天气刚刚好,我又带着爸妈出了趟门。算上这次,是陪他们走...
百度沈抖:未来 90% 工作都... “未来90%的工作,都可能有智能体深度参与、协助完成。”在百度AIDAY百度搭子专场上,百度集团执行...
港股风向标|恒指短线放量滞涨 ... 财联社7月10日讯(编辑 冯轶)今日港股再度冲高回落,三大指数午后集体走弱。截至收盘,恒生指数、国企...
MLCC周期全面爆发!风华高科... 7月10日,国内被动元件龙头风华高科(000636.SZ)披露2026年半年度业绩预告,上半年净利润...
关停杠杆炒金!银行个人贵金属代... 今年6月以来,交通银行、招商银行、工商银行、建设银行等多家银行相继发布公告,宣布将于7月下旬起停办代...
原创 许... 许家印当年为何跟黄有龙搞在一起?背后到底有何猫腻?许家印跟黄有龙堪称是中国资本市场的两大奇人。一个凭...
世界杯第29日前瞻:西班牙vs... 北京时间7月11日凌晨3点,2026年美加墨世界杯进入第29个比赛日的争夺,将展开第二场1/4决赛争...
食品饮料周报:白酒去库存加速,... 证券之星食品饮料行业周报:2026年7月6日-2026年7月10日,沪深300指数下跌1.27%,申...
沈阳闲置黄金变现爆发,宏昇贵金... 近期,国际黄金价格持续震荡上行,沈阳地区贵金属回收市场迎来交易热潮。随着居民家庭闲置黄金存量的释放,...
Claude Code “高危... 出品 | 妙投APP 作者 | 张贝贝 编辑 | 丁萍 头图 | AI生图 7月8日,一则关于Cla...
新豪轩门窗X新华网《极致中国造... 从“中国制造”的规模优势迈向“中国创造”的价值跃升,中国品牌正以持续创新重塑全球竞争力。在这一进程中...
上市械企董事长,被女儿、女婿联... 来源:医疗器械经销商联盟 7月8日,科创板上市公司奥精医疗突发重磅公告,瞬间引爆资本市场与舆论圈。公...
汕头市优佳适科技有限公司成立 ... 天眼查App显示,近日,汕头市优佳适科技有限公司成立,注册资本50万人民币,经营范围为一般项目:技术...
砍掉两百个BU与近千家代持外壳... 在智能清洁硬件赛道凭借激进出海与疯狂营销一路狂飙的追觅(Dreame),突然在资本市场的前夜迎来了最...
原创 昨... 美东时间 7 月 9 日夜,纽约债市收盘钟声敲响时,交易大厅里紧绷了一周的情绪终于松了下来。本周总额...
段永平再次增持泡泡玛特 持股比... 观点网讯:7月10日,据港交所披露,知名投资人段永平再度增持泡泡玛特股票。 此次增持后,段永平持股数...
包揽全球80%的产能,又一个行... 作者: 快刀财经 郑栾 近日,新消费行业又迎来一笔久违的大额融资——咖爷科技宣布完成B轮融资,由美...
外储增配香港资产,可能会买啥? 界面新闻记者 | 杨志锦 界面新闻编辑 | 王姝 本周,央行行长潘功胜在香港的讲话引起市场广泛关...
最贵一套1.5亿,上海徐汇两大... 界面新闻记者 | 王婷婷 上海顶豪市场年度大戏来了。 7月11日,上海西岸美高梅酒店将迎来两大豪宅...