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

本文通过IDistributedCache的接口方法,实现Redis与MemoryCache统一帮助类。只需要在配置文件中简单的配置一下,就可以实现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,还是Redis,MemoryCache不支持分布式,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);}
}

总结

暂无,下次再会

相关内容

热门资讯

蜻蜓订购APP贵金属订购非法期...   蜻蜓订购APP以"投资平台"名义对外宣传,主打贵金属期货(订购)交易。该平台一方面强调自身"正规...
悟空订购APP非法期货交易欺骗...   近期,有投资者反映,“悟空订购APP”等平台以白银、贵金属订购为名,宣传所谓“高收益”“低门槛”...
小赢淘金APP期货投资骗局,平...   “小赢淘金”之流,最擅长的就是用“注册送现金”、“充值返券”的糖衣炮弹来引流。别天真地以为那是福...
八方淘金APP非法期货交易欺骗...   警惕!八方生财、每日淘金、小赢淘金、悟空订购、蜻蜓订购、斗金订购等APP均涉嫌非法期货交易!  ...
智易购APP贵金属订购交易骗局...   很多人看到“3元起投”“充值送福利”“操作简单”“随时提现”这类宣传,很容易把智易购APP当成普...
喜玛银庄APP商品订购投资骗局...   喜玛银庄APP白银、铂金“现货订购”骗局警示:无资质平台涉嫌非法期货交易,投资者爆仓后如何维权?...
吉鑫乐享APP炒贵金属订购交易...   近期,多名投资者反映在“吉鑫乐享APP”进行贵金属投资时遭遇严重亏损,甚至血本无归。看似正规的“...
易掘金APP虚假期货投资骗局,...   “易掘金”的APP它打着“高收益、灵活投资”的旗号,宣称通过“商品订购”就能轻松赚钱,吸引了不少...
在大吉订购APP订购交易亏损被...   近期,不少投资者反映在“大吉订购App”上投资白银、铂金等商品遭遇严重亏损。该平台宣称提供现货订...
铂银壹号APP商品订购交易亏损...   许多中小投资者误以为网上的“商品现货订购”是合规合法的理财渠道,殊不知这背后隐藏着巨大的合规风险...
兴鑫淘金APP贵金属订购交易亏...   白银、贵金属或其他商品类投资,除国家批准的正规期货交易场所及持牌期货公司外,市面上大量第三方交易...
铂银掘金APP无资质的违规平台...   铂银掘金等平台的投资者,往往是被“注册送现金”“充值返现券”“首单免亏”等广告话术吸引,进而下载...
八方淘金APP订购交易不合规,...   “八方淘金APP”“铂银掘金APP”“铂银壹号APP”等软件被指以“现货订购”为名,实际采用高杠...
在指尖订购APP订购商品亏损被...   指尖订购APP这类平台,表面是“订购交易”,实则是披着电商外衣的非法期货陷阱。绝大多数投资者被蒙...
在犀贝易购APP做商品订购交易...   市面上打着“现货投资”“贵金属交易”旗号的APP并不少,但真正合规、受监管的平台并不多。犀贝易购...
易达淘金APP虚假商品订购交易...   易达淘金APP存在严重的虚假宣传与违规交易行为。该平台打着“商品订购”的旗号,实则通过不合规的交...
大浪淘金APP白银订购亏损被骗...   大浪淘金APP最隐蔽的套路,在于其完全封闭的内盘交易系统。表面上,它宣称与国际贵金属市场接轨;实...
一品好购APP上订购白银出现亏...   一品好购APP原名“一品订购”,运营方为上海宝智未来信息技术有限公司。近期不少投资者反映在该平台...
九州订购APP贵金属订购投资骗...   九州订购APP正通过抖.音、快手、今日头条等平台大量投放投资广告,用“5元起投”“充值返现”“0...
坚锅淘金APP交易软件并不正规...   当前,市面上大量所谓的“现货商城订购”交易软件,早已偏离了正常的实物商品买卖,演变为高杠杆、高手...