关于Redis分布式缓存 IDistributedCache 的工具类
通过NuGet 安装 Microsoft.Extensions.Caching.StackExchangeRedis 组件
在 Program.cs 的 builder.Build() 之前注册 IDistributedCache 服务
1 2 3 4 5 6 7 | string redisConnection = builder.Configuration.GetConnectionString( "RedisConnection" ); //注册分布式Redis builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = redisConnection; options.InstanceName = "yzk_" ; }); |
appsetting.json配置文件
1 2 3 4 5 | "ConnectionStrings" : { "DefaultConnection" : "Server=DESKTOP-DABHN6U\\MSSQLSERVER2014;uid=sa;pwd=Lz38275292;database=NewAps;MultipleActiveResultSets=true;" , "RedisConnection" : "127.0.0.1:6379" } |
工具类接口
1 2 3 4 5 6 7 8 9 10 11 12 13 | using Microsoft.AspNetCore.Routing.Template; using Microsoft.Extensions.Caching.Distributed; namespace TestWebApplication.Utility { public interface IDistributedCacheHelper { TResult? GetOrCreate<TResult>( string cacheKey, Func<DistributedCacheEntryOptions, TResult?> valueFactory, int expireSeconds = 60); Task<TResult?> GetOrCreateAsync<TResult>( string cacheKey, Func<DistributedCacheEntryOptions, Task<TResult?>> valueFactory, int expireSeconds); void Remove( string cacheKey); Task RemoveAsync( string cacheKey); } } |
工具类实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | using Microsoft.Extensions.Caching.Distributed; using System.Text.Json; namespace TestWebApplication.Utility { /// <summary> /// 分布式Redis的IDistributedCache工具类 /// </summary> public class DistributedCacheHelper : IDistributedCacheHelper { private readonly IDistributedCache m_Cache; public DistributedCacheHelper(IDistributedCache cache) { m_Cache = cache; } private static DistributedCacheEntryOptions CreateOptions( int baseExpireSeconds) { double sec = Random.Shared.Next(baseExpireSeconds, baseExpireSeconds * 2); TimeSpan expiration = TimeSpan.FromSeconds(sec); var options = new DistributedCacheEntryOptions(); options.AbsoluteExpirationRelativeToNow = expiration; return options; } public TResult? GetOrCreate<TResult>( string cacheKey, Func<DistributedCacheEntryOptions, TResult?> valueFactory, int expireSeconds = 60) { throw new NotImplementedException(); } public async Task<TResult?> GetOrCreateAsync<TResult>( string cacheKey, Func<DistributedCacheEntryOptions, Task<TResult?>> valueFactory, int expireSeconds) { string jsonStr = await m_Cache.GetStringAsync(cacheKey); if ( string .IsNullOrEmpty(jsonStr)) { var options = CreateOptions(expireSeconds); TResult? result = await valueFactory(options); string jsonOfResult = JsonSerializer.Serialize(result, typeof (TResult)); await m_Cache.SetStringAsync(cacheKey, jsonOfResult, options); return result; } else { await m_Cache.RefreshAsync(cacheKey); return JsonSerializer.Deserialize<TResult>(jsonStr); } } public void Remove( string cacheKey) { m_Cache.Remove(cacheKey); } public async Task RemoveAsync( string cacheKey) { await m_Cache.RemoveAsync(cacheKey); } } } |
客户端调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Distributed; using TestWebApplication.Utility; namespace TestWebApplication.Controllers { [Route( "api/[controller]" )] [ApiController] public class Test1Controller : ControllerBase { //分布式Redis private readonly ILogger<Test1Controller> _logger; private readonly IDistributedCacheHelper _distributedCache; public Test1Controller(ILogger<Test1Controller> logger, IDistributedCacheHelper distributedCache) { _logger = logger; _distributedCache = distributedCache; } [HttpGet] public async Task< string > Now() { string KEY = "Now" ; string ? s = String.Empty; s = await _distributedCache.GetOrCreateAsync(KEY, async (e) => { return DateTime.Now.ToString(); }, 60); return s; } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义