造轮子之缓存
1.Asp.Net Core造轮之旅:逐步构建自己的开发框架-目录2.asp.net core之Startup3.asp.net core之依赖注入4.asp.net core之中间件5.asp.net core之Host6.asp.net core之Kestrel7.asp.net core之配置8.asp.net core之Options9.asp.net core之日志10.asp.net core之路由11.asp.net core之异常处理12.asp.net core之HttpClient13.asp.net core之实时应用14.asp.net core之EfCore15.造轮子之自动依赖注入16.造轮子之日志17.造轮子之统一业务异常处理18.造轮子之统一请求响应格式
19.造轮子之缓存
20.造轮子之ORM集成21.造轮子之asp.net core identity22.造轮子之自定义授权策略23.造轮子之权限管理24.造轮子之多语言管理25.造轮子之角色管理26.造轮子之用户管理27.造轮子之菜单管理28.造轮子之属性注入配合懒加载构建服务抽象基类29.造轮子之EventBus30.造轮子之消息实时推送31.造轮子之种子数据32.造轮子之集成GraphQL33.造轮子之设置管理34.造轮子之文件管理35.造轮子之单层应用总结篇36.单层应用升级到多层应用137.单层应用升级到多层应用238.单层应用升级到多层应用3缓存也是在业务开发过程中经常使用的一环。
在Asp.net core中,原生包含了MemoryCache内存缓存和DistributedCache分布式缓存两种缓存。
在Program中添加以下代码注册服务之后即可使用依赖注入使用两种缓存。
builder.Services.AddMemoryCache();
var redis = await ConnectionMultiplexer.ConnectAsync(builder.Configuration["Cache:Redis"]);
builder.Services.AddSingleton<IConnectionMultiplexer, ConnectionMultiplexer>(_ => redis);
builder.Services.AddStackExchangeRedisCache(options =>
{
options.ConnectionMultiplexerFactory = async () => await Task.FromResult(redis);
});
使用时只需要注入IMemoryCache或者IDistributedCache即可使用。
注意这里需要添加Microsoft.AspNetCore.DataProtection.StackExchangeRedis的nuget包。
扩展IDistributedCache#
在原生使用中IDistributedCache不支持泛型GetSet,只能先序列化成字符串再操作。而IMemoryCache却可以,所以为了统一操作习惯,我们来扩展一下IDistributedCache。
添加一个DistributedCacheExtension类。
using System.Text.Json;
namespace Microsoft.Extensions.Caching.Distributed
{
public static class DistributedCacheExtension
{
public static async Task<T> GetAsync<T>(this IDistributedCache cache, string key, CancellationToken cancellationToken = default)
{
var value = await cache.GetStringAsync(key, cancellationToken);
if (string.IsNullOrWhiteSpace(value))
return default(T);
return JsonSerializer.Deserialize<T>(value);
}
public static async Task SetAsync<T>(this IDistributedCache cache, string key, T value, CancellationToken cancellationToken = default)
{
await cache.SetStringAsync(key, JsonSerializer.Serialize(value), cancellationToken);
}
public static async Task SetAsync<T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions distributedCacheEntryOptions, CancellationToken cancellationToken = default)
{
await cache.SetStringAsync(key, JsonSerializer.Serialize(value), distributedCacheEntryOptions, cancellationToken);
}
public static async Task SetAbsoluteExpirationRelativeToNowAsync<T>(this IDistributedCache cache, string key, T value, TimeSpan timeSpan, CancellationToken cancellationToken = default)
{
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = timeSpan
};
await cache.SetStringAsync(key, JsonSerializer.Serialize(value), options, cancellationToken);
}
public static async Task SetAbsoluteExpirationAsync<T>(this IDistributedCache cache, string key, T value, DateTimeOffset dateTimeOffset, CancellationToken cancellationToken = default)
{
var options = new DistributedCacheEntryOptions
{
AbsoluteExpiration = dateTimeOffset
};
await cache.SetStringAsync(key, JsonSerializer.Serialize(value), options, cancellationToken);
}
public static async Task SetSlidingExpirationAsync<T>(this IDistributedCache cache, string key, T value, TimeSpan slidingExpiration, CancellationToken cancellationToken = default)
{
var options = new DistributedCacheEntryOptions
{
SlidingExpiration = slidingExpiration
};
await cache.SetStringAsync(key, JsonSerializer.Serialize(value), options, cancellationToken);
}
}
}
这里我们使用System.Text.Json封装一下序列化的读写操作。顺带封装一下过期机制。
这里命名空间也使用Microsoft.Extensions.Caching.Distributed,这样我们就不需要再额外using命名空间才能使用这些扩展方法了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?