分布式缓存\appsettings.Development.json
| { |
| "Logging": { |
| "LogLevel": { |
| "Default": "Information", |
| "Microsoft.AspNetCore": "Warning" |
| } |
| } |
| } |
| |
分布式缓存\appsettings.json
| { |
| "Logging": { |
| "LogLevel": { |
| "Default": "Information", |
| "Microsoft.AspNetCore": "Warning" |
| } |
| }, |
| "AllowedHosts": "*" |
| } |
| |
分布式缓存\DistributedCacheHelper.cs
| using Microsoft.Extensions.Caching.Distributed; |
| using System; |
| using System.Text; |
| using System.Text.Json; |
| using System.Threading.Tasks; |
| |
| namespace Zack.ASPNETCore |
| { |
| public class DistributedCacheHelper : IDistributedCacheHelper |
| { |
| private readonly IDistributedCache distCache; |
| |
| public DistributedCacheHelper(IDistributedCache distCache) |
| { |
| this.distCache = distCache; |
| } |
| |
| private static DistributedCacheEntryOptions CreateOptions(int baseExpireSeconds) |
| { |
| |
| double sec = Random.Shared.Next(baseExpireSeconds, baseExpireSeconds * 2); |
| TimeSpan expiration = TimeSpan.FromSeconds(sec); |
| DistributedCacheEntryOptions options = new DistributedCacheEntryOptions(); |
| options.AbsoluteExpirationRelativeToNow = expiration; |
| return options; |
| } |
| |
| public TResult? GetOrCreate<TResult>(string cacheKey, Func<DistributedCacheEntryOptions, TResult?> valueFactory, int expireSeconds = 60) |
| { |
| string jsonStr = distCache.GetString(cacheKey); |
| |
| if (string.IsNullOrEmpty(jsonStr)) |
| { |
| var options = CreateOptions(expireSeconds); |
| TResult? result = valueFactory(options); |
| |
| string jsonOfResult = JsonSerializer.Serialize(result, |
| typeof(TResult)); |
| distCache.SetString(cacheKey, jsonOfResult, options); |
| return result; |
| } |
| else |
| { |
| |
| |
| |
| |
| distCache.Refresh(cacheKey); |
| return JsonSerializer.Deserialize<TResult>(jsonStr)!; |
| } |
| } |
| |
| |
| public async Task<TResult?> GetOrCreateAsync<TResult>(string cacheKey, Func<DistributedCacheEntryOptions, Task<TResult?>> valueFactory, int expireSeconds = 60) |
| { |
| string jsonStr = await distCache.GetStringAsync(cacheKey); |
| if (string.IsNullOrEmpty(jsonStr)) |
| { |
| var options = CreateOptions(expireSeconds); |
| TResult? result = await valueFactory(options); |
| string jsonOfResult = JsonSerializer.Serialize(result,typeof(TResult)); |
| await distCache.SetStringAsync(cacheKey, jsonOfResult, options); |
| return result; |
| } |
| else |
| { |
| await distCache.RefreshAsync(cacheKey); |
| return JsonSerializer.Deserialize<TResult>(jsonStr)!; |
| } |
| } |
| |
| |
| public void Remove(string cacheKey) |
| { |
| distCache.Remove(cacheKey); |
| } |
| |
| public Task RemoveAsync(string cacheKey) |
| { |
| return distCache.RemoveAsync(cacheKey); |
| } |
| } |
| } |
| |
分布式缓存\IDistributedCacheHelper.cs
| using Microsoft.Extensions.Caching.Distributed; |
| using System; |
| using System.Threading.Tasks; |
| |
| namespace Zack.ASPNETCore |
| { |
| 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 = 60); |
| |
| void Remove(string cacheKey); |
| Task RemoveAsync(string cacheKey); |
| } |
| } |
| |
分布式缓存\Program.cs
| using Zack.ASPNETCore; |
| |
| var builder = WebApplication.CreateBuilder(args); |
| |
| |
| |
| builder.Services.AddControllers(); |
| |
| builder.Services.AddEndpointsApiExplorer(); |
| builder.Services.AddSwaggerGen(); |
| builder.Services.AddStackExchangeRedisCache(options => |
| { |
| options.Configuration = "localhost:6379"; |
| options.InstanceName = "pre_"; |
| }); |
| builder.Services.AddScoped<IDistributedCacheHelper, DistributedCacheHelper>(); |
| |
| var app = builder.Build(); |
| |
| |
| if (app.Environment.IsDevelopment()) |
| { |
| app.UseSwagger(); |
| app.UseSwaggerUI(); |
| } |
| |
| app.UseHttpsRedirection(); |
| |
| app.UseAuthorization(); |
| |
| app.MapControllers(); |
| |
| app.Run(); |
| |
| |
分布式缓存\分布式缓存.csproj
| <Project Sdk="Microsoft.NET.Sdk.Web"> |
| |
| <PropertyGroup> |
| <TargetFramework>net6.0</TargetFramework> |
| <Nullable>enable</Nullable> |
| <ImplicitUsings>enable</ImplicitUsings> |
| </PropertyGroup> |
| |
| <ItemGroup> |
| <PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="6.0.0" /> |
| <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" /> |
| </ItemGroup> |
| |
| </Project> |
| |
分布式缓存\Controllers\Test1Controller.cs
| using Microsoft.AspNetCore.Mvc; |
| using Microsoft.Extensions.Caching.Distributed; |
| using Zack.ASPNETCore; |
| |
| namespace 分布式缓存.Controllers |
| { |
| [ApiController] |
| [Route("[controller]/[action]")] |
| public class Test1Controller : ControllerBase |
| { |
| private readonly IDistributedCache distCache; |
| private readonly IDistributedCacheHelper helper; |
| public Test1Controller(IDistributedCache distCache, IDistributedCacheHelper helper) |
| { |
| this.distCache = distCache; |
| this.helper = helper; |
| } |
| [HttpGet] |
| public string Now() |
| { |
| string s = distCache.GetString("Now"); |
| if (s == null) |
| { |
| s = DateTime.Now.ToString(); |
| var opt = new DistributedCacheEntryOptions(); |
| opt.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(180); |
| distCache.SetString("Now", s, opt); |
| } |
| return s; |
| } |
| |
| [HttpGet] |
| public Task<string?> Now2() |
| { |
| return helper.GetOrCreateAsync<string>("Now2", async e => DateTime.Now.ToString()); |
| } |
| |
| } |
| } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析