net6使用StackExchangeRedis实现分布式缓存

news/2025/2/13 5:33:49/

上一篇讲解了Redis的搭建及ServiceStack.Redis 与 StackExchange.Reids 的区别https://blog.csdn.net/qq_39569480/article/details/105249607

这篇文章遗我们来说下使用Microsoft.Extensions.Caching.StackExchangeRedis来对redis进行操作及帮助类。

首先在windows上安装redis 在上边连接中有教程 .

创建webapi项目
在这里插入图片描述

在包管理器中安装Microsoft.Extensions.Caching.StackExchangeRedis
在这里插入图片描述
在appsettings.json中添加连接字符串:(redis连接字符串)

  "ConnectionStrings": {"Redis": "123.123.33.22:6379,password=123456!,ConnectTimeout=15000,SyncTimeout=5000"},

定义一个接口

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="minutes">过期时间间隔 以分钟为单位</param>void SetCache(string key, object value,int minutes);/// <summary>/// 设置缓存/// 注:默认过期类型为绝对过期/// </summary>/// <param name="key">缓存Key</param>/// <param name="value">值</param>/// <param name="timeout">过期时间间隔 以分钟为单位</param>Task SetCacheAsync(string key, object value, int minutes);/// <summary>/// 设置缓存/// 注:默认过期类型为绝对过期/// </summary>/// <param name="key">缓存Key</param>/// <param name="value">值</param>/// <param name="minutes">过期时间间隔 以分钟为单位</param>/// <param name="expireType">过期类型</param>  void SetCache(string key, object value, int minutes, ExpireType expireType);/// <summary>/// 设置缓存/// 注:默认过期类型为绝对过期/// </summary>/// <param name="key">缓存Key</param>/// <param name="value">值</param>/// <param name="minutes">过期时间间隔 以分钟为单位</param>/// <param name="expireType">过期类型</param>  Task SetCacheAsync(string key, object value, int minutes, 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"></param>/// <param name="value"></param>/// <param name="minutes"></param>/// <param name="expireType">过期类型,默认绝对过期</param>/// <returns></returns>Task<string> GetOrAddAsync(string key, object value, int minutes, ExpireType expireType = 0);/// <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);/// <summary>/// 获取泛型缓存,没有则添加/// </summary>/// <typeparam name="T"></typeparam>/// <param name="key"></param>/// <param name="value"></param>/// <param name="minutes"></param>/// <param name="expireType">过期类型,默认绝对过期</param>/// <returns></returns>Task<T> GetOrAddAsync<T>(string key, object value, int minutes, ExpireType expireType = 0);#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
}

实现接口中定义的方法

public class CacheHelper : ICache
{readonly IDistributedCache _cache;public CacheHelper(IDistributedCache cache){_cache = cache;}protected string BuildKey(string idKey){return $"Cache_{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,int minutes){string cacheKey = BuildKey(key);_cache.SetString(cacheKey, value.ToJson(), new DistributedCacheEntryOptions{AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes)});}public async Task SetCacheAsync(string key, object value, int minutes){string cacheKey = BuildKey(key);await _cache.SetStringAsync(cacheKey, value.ToJson(), new DistributedCacheEntryOptions{AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes)});}public void SetCache(string key, object value, int minutes, ExpireType expireType){string cacheKey = BuildKey(key);if (expireType == ExpireType.Absolute){//这里没转换标准时间,Linux时区会有问题?_cache.SetString(cacheKey, value.ToJson(), new DistributedCacheEntryOptions{AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes)});}else{_cache.SetString(cacheKey, value.ToJson(), new DistributedCacheEntryOptions{AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(minutes)});}}public async Task SetCacheAsync(string key, object value, int minutes, ExpireType expireType){string cacheKey = BuildKey(key);if (expireType == ExpireType.Absolute){//这里没转换标准时间,Linux时区会有问题?await _cache.SetStringAsync(cacheKey, value.ToJson(), new DistributedCacheEntryOptions{AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes)});}else{await _cache.SetStringAsync(cacheKey, value.ToJson(), new DistributedCacheEntryOptions{AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(minutes)});}}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 async Task<string> GetOrAddAsync(string key,object value,int minutes, ExpireType expireType=0){if (key.IsNullOrEmpty()) return null;string cacheKey = BuildKey(key);var cache = await _cache.GetStringAsync(cacheKey);if (cache==null&& value!=null){string json= value.ToJson();if (expireType == ExpireType.Absolute){//这里没转换标准时间,Linux时区会有问题?await _cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions{AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes)});}else{await _cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions{AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(minutes)});}return json;}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 async Task<T> GetOrAddAsync<T>(string key, object value, int minutes, ExpireType expireType = 0){if (key.IsNullOrEmpty()) return default(T);string cacheKey = BuildKey(key);var cache = await _cache.GetStringAsync(cacheKey);if (cache == null && value != null){string json = value.ToJson();if (expireType == ExpireType.Absolute){//这里没转换标准时间,Linux时区会有问题?await _cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions{AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes)});}else{await _cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions{AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(minutes)});}return json.ToObject<T>();}return cache.ToObject<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));}
}

定义一个枚举的过期类型

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

定义一个string的扩展方法

public static class ValueToObject
{/// <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);}/// <summary>/// 将字符串序列化为json/// </summary>/// <param name="str"></param>/// <returns></returns>public static string ToJson(this object str){return JsonConvert.SerializeObject(str);}
}

在Program.cs文件中注入并添加redis

builder.Services.AddScoped(typeof(ICache), typeof(CacheHelper));//注入builder.Services.AddStackExchangeRedisCache(o =>
{//redis连接o.Configuration = builder.Configuration.GetConnectionString("Redis");//设置缓存key的前缀//o.InstanceName = "";
});

控制器中使用

[Route("demo")]
[ApiController]
//[Authorize]
public class DemoController : ControllerBase
{private readonly IDemoService _demo;public DemoController(IDemoService demo){_demo = demo;}/// <summary>/// 获取列表/// </summary>/// <param name="input"></param>/// <returns></returns>[HttpGet]public async Task<dynamic> Get(int id){DemoGetOutPut demo=await _cache.GetOrAddAsync<DemoGetOutPut>($"demo{id}", async () => await GetDemo(id),20);return demo;}public async Task<dynamic> Get(int id){return new { name= "张三", age= 18 };}
}

http://www.ppmy.cn/news/1276347.html

相关文章

5G+云渲染技术:将如何快速推进XR和元宇宙?

XR&#xff08;扩展现实&#xff09;领域正在以惊人的速度增长。目前&#xff0c;到 2024 年&#xff0c;一些专家表示这个行业的价值将达到 3000 亿美元。 这个行业发展如此迅速的部分原因是 XR 将在商业环境中的带来巨大利益。近年来&#xff0c;很多企业遇到了将增强现实和…

网络世界的黑暗角落:常见漏洞攻防大揭秘

网络世界的黑暗角落&#xff1a;常见漏洞攻防大揭秘 今天带来了网站常见的漏洞总结,大家在自己的服务器上也需要好好进行防护,密码不要过于简单.不然非常容易遭到攻击,最终达到不可挽回的损失.很多黑客想网络乞丐一样将你服务器打宕机,然后要求你进行付费.不知道大家有没有遇到…

BKP 备份寄存器 RTC 实时时钟-stm32入门

这一章节我们要讲的主要内容是 RTC 实时时钟&#xff0c;对应手册&#xff0c;是第 16 章的位置。 实时时钟这个东西&#xff0c;本质上是一个定时器&#xff0c;但是这个定时器&#xff0c;是专门用来产生年月日时分秒&#xff0c;这种日期和时间信息的。所以学会了 STM32 的…

Databend 开源周报第 124 期

Databend 是一款现代云数仓。专为弹性和高效设计&#xff0c;为您的大规模分析需求保驾护航。自由且开源。即刻体验云服务&#xff1a;https://app.databend.cn 。 Whats On In Databend 探索 Databend 本周新进展&#xff0c;遇到更贴近你心意的 Databend 。 新增对 Delta 和…

智能优化算法应用:基于非洲秃鹫算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于非洲秃鹫算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于非洲秃鹫算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.非洲秃鹫算法4.实验参数设定5.算法结果6.…

Java经典面试题:冒泡算法的使用

Hi i,m JinXiang ⭐ 前言 ⭐ 本篇文章主要介绍Java经典面试题&#xff1a;冒泡算法的使用以及部分理论知识 &#x1f349;欢迎点赞 &#x1f44d; 收藏 ⭐留言评论 &#x1f4dd;私信必回哟&#x1f601; &#x1f349;博主收将持续更新学习记录获&#xff0c;友友们有任何问题…

go语言函数二、init函数定义与作用

go语言init函数定义与作用 在go语言中&#xff0c;每一个源文件都可以包含一个init函数&#xff0c;这个函数会在main函数执行前&#xff0c;被go运行框架调用&#xff0c;注意是在main函数执行前。 package main import ("fmt" )func init() {fmt.Println("i…

【PostgreSQL内核学习(十八)—— 存储管理(存储管理的体系结构)】

存储管理 概述存储管理器的体系结构存储管理器的主要任务读写元组过程 声明&#xff1a;本文的部分内容参考了他人的文章。在编写过程中&#xff0c;我们尊重他人的知识产权和学术成果&#xff0c;力求遵循合理使用原则&#xff0c;并在适用的情况下注明引用来源。 本文主要参考…