首页 > 其他分享 >造轮子之缓存

造轮子之缓存

时间:2023-10-08 17:03:00浏览次数:33  
标签:cancellationToken 缓存 cache value key IDistributedCache 轮子 options

缓存也是在业务开发过程中经常使用的一环。
在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命名空间才能使用这些扩展方法了。

欢迎进群催更。

image.png

标签:cancellationToken,缓存,cache,value,key,IDistributedCache,轮子,options
From: https://www.cnblogs.com/fanshaoO/p/17749590.html

相关文章

  • python dict和ttl支持自动过期缓存
    pythondict和ttl支持自动过期缓存 github: https://github.com/mailgun/expiringdict 安装pipinstallexpiringdictpipinstallexpiring-dict使用:fromexpiringdictimportExpiringDictfromdatetimeimporttimedelta#创建一个带有过期时间的字典,过期时间......
  • 造轮子之自动依赖注入
    在我们造轮子的起初,基建非常重要,而依赖注入是我们使用频率最高的一项,频繁的手动注入太麻烦,所以我们来实现一下自动化注入。技术选型在ASP.NETCore中,有两种常见的依赖注入方式:原生依赖注入和三方依赖注入。原生依赖注入ASP.NETCore提供了一个内置的依赖注入容器,可以用于......
  • 造轮子之日志
    在日常使用中日志也是我们必不可少的一环,在原生日志组件中支持的日志驱动比较少,所以我们需要使用一些三方日志组件来扩展我们的日志记录。集成Serilog三方日志组件有很多,如NLOG,LOG4NET等等,这里个人习惯,使用Serilog。Serilog的集成方式非常简单。安装Nuget包Serilog.AspNetCor......
  • 造轮子之统一业务异常处理
    异常处理也是我们必不可少的一环,借助Asp.netCore的UseExceptionHandler中间件,我们可以很轻易的配置我们的业务异常处理逻辑。自定义业务异常类首先我们定义一个业务异常类,继承Exception,添加一个Code状态码属性,和MessageData数组,这个数组用于Format异常信息。在实际业务场景中可......
  • 造轮子之统一请求响应格式
    在上文中我们实现了统一业务异常处理,在异常响应中我们也使用了统一的响应格式返回给客户端。接下来我们就讲一下约定统一的氢气响应格式。在业务开发中,一个规范统一的请求响应格式可以提高我们的前后端开发对接效率,同时清晰的结构提高了可读性。响应基类首先定义一个最基础的只......
  • discuz关闭缓存
    修改 function_core.php文件vimdiscuz_x3.2/upload/source/function/function_core.php代码如下,添加红色字体登录后复制functionchecktplrefresh($maintpl,$subtpl,$timecompare,$templateid,$cachefile,$tpldir,$file){static$tplrefresh,$timestamp,$......
  • 缓存(Redis)与数据库(MySQL)一致性如何解决?
    【零】场景预设我们以12306购票系统为例,结合购票场景完成缓存与数据库双写一致性的相关问题解决【一】业务背景为了满足用户对一趟列车不同站点不同座位类型的余量查询需求,我们采取了一种优化方案。我们将这些余量信息存储在缓存中,以便用户可以快速查询。然而,在用户创建......
  • Redis学习之缓存雪崩、缓存击穿及封装Redis工具类
    缓存雪崩缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机,导致大量请求到达数据库,带来巨大压力。解决思路:1.不让key同时失效2.尽量不让Redis宕机具体解决方案:缓存击穿又叫热点key失效:两种解决方案:1.互斥锁:只有一个线程会负责缓存重建,其余线程拿不到锁,就......
  • 202310061227-《心得:低版本mysql配置一,些轮子插件》
    1.对于mysql5.7.42,驱动(connector)选择:5.1.46。2.测试链接时:useSSL=true&enabledTLSProtocols=TLSv1.1 驱动链接字符串上要拼接上。3.驱动链接字符串:高版本mysql,意味着高版本connector,选>=8;低版本,选择5.x;               高版本mysql,com.my......
  • 什么是缓存雪崩、缓存击穿、缓存穿透?如何解决
    前言Redis作为目前使用最广泛的缓存,相信大家都不陌生。但是使用缓存并没有这么简单,还要考虑缓存雪崩,缓存击穿,缓存穿透的问题,什么是缓存雪崩,击穿,穿透呢,又怎么解决这些问题呢。缓存雪崩什么是缓存雪崩?当某一个时刻出现大规模的缓存失效的情况,那么就会导致大量的请求直接打在数据......