源代码怎么做网站,注册实名认证,上海企业名录 企业黄页,环保局网站建设前言我们在项目中使用Redis时通常是写一个单例模式的RedisHelper静态类#xff0c;暴露一些常用的Get、Set等操作#xff0c;在需要使用地方直接RedisHelper.StringGet(xx,xx)就可以了#xff0c;这样虽然简单粗暴地满足我们对Redis的所有操作需要#xff0c;但是这在Asp.N… 前言我们在项目中使用Redis时通常是写一个单例模式的RedisHelper静态类暴露一些常用的Get、Set等操作在需要使用地方直接RedisHelper.StringGet(xx,xx)就可以了这样虽然简单粗暴地满足我们对Redis的所有操作需要但是这在Asp.Net Core的项目显得不是那么优雅了。首先你的RedisHelper静态类无法使用Asp.Net Core容器又如何优雅的通过依赖注入获取IConfiguration中的配置项呢既然我们使用Asp.Net Core这么优秀的框架最佳实践当然就是遵循官方建议的开发规范优雅的编写代码。IDistributedCache若要使用 SQL Server 分布式缓存请添加对 Microsoft.Extensions.Caching.SqlServer 包的包引用。若要使用 Redis 分布式缓存请添加对 Microsoft.Extensions.Caching.StackExchangeRedis 包的包引用。若要使用 NCache 分布式缓存请添加对 NCache.Microsoft.Extensions.Caching.OpenSource 包的包引用。无论选择哪种实现应用都将使用 IDistributedCache 接口与缓存进行交互。来看下IDistributedCache这个接口的定义namespace Microsoft.Extensions.Caching.Distributed;/// summary
/// Represents a distributed cache of serialized values.
/// /summary
public interface IDistributedCache
{/// summary/// Gets a value with the given key./// /summarybyte[]? Get(string key);/// summary/// Gets a value with the given key./// /summaryTaskbyte[]? GetAsync(string key, CancellationToken token default(CancellationToken));void Set(string key, byte[] value, DistributedCacheEntryOptions options);/// summary/// Sets the value with the given key./// /summaryTask SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token default(CancellationToken));/// summary/// Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any)./// /summaryvoid Refresh(string key);/// summary/// Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any)./// /summaryTask RefreshAsync(string key, CancellationToken token default(CancellationToken));/// summary/// Removes the value with the given key./// /summaryvoid Remove(string key);/// summary/// Removes the value with the given key./// /summaryTask RemoveAsync(string key, CancellationToken token default(CancellationToken));
}IDistributedCache 接口提供以下方法来处理分布式缓存实现中的项Get、GetAsync如果在缓存中找到则接受字符串键并以 byte[] 数组的形式检索缓存项。Set、SetAsync使用字符串键将项作为 byte[] 数组添加到缓存。Refresh、RefreshAsync根据键刷新缓存中的项重置其可调到期超时如果有。Remove、RemoveAsync根据字符串键删除缓存项。干掉RedisHelper官方不仅提出了如何最佳实践分布式缓存的使用还提供了基本的实现库给我们直接用比如我们在项目中用Redis为我们提供缓存服务添加引用Microsoft.Extensions.Caching.StackExchangeRedis注册容器AddStackExchangeRedisCache并配置参数builder.Services.AddStackExchangeRedisCache(options {options.Configuration builder.Configuration.GetConnectionString(MyRedisConStr);options.InstanceName SampleInstance;});在需要使用Redis的地方通过构造函数注入IDistributedCache实例调用即可这样就可以优雅的使用Redis了更加符合Asp.Net Core的设计风格养成通过容器注入的方式来调用我们的各种服务而不是全局使用RedisHelper静态类通过IOC的方式结合面向接口开发能方便的替换我们的实现类统一由容器提供对象的创建这种控制反转带来的好处只可意会不可言传这里就不赘述了。AddStackExchangeRedisCache到底干了什么上面已经知道如何优雅的使用我们的Redis了但是不看下源码就不知道底层实现总是心里不踏实的。源码比较好理解的因为这个Nuget包的源码也就四个类而上面注册容器的逻辑也比较简单AddStackExchangeRedisCache主要干的活// 1.启用Options以使用IOptions
services.AddOptions();
// 2.注入配置自定义配置可以通过IOptionsT注入到需要使用该配置的地方
services.Configure(setupAction);
// 3.注入一个单例IDistributedCache的实现类RedisCache
services.Add(ServiceDescriptor.SingletonIDistributedCache, RedisCache());所以我们在需要用Redis的地方通过构造函数注入IDistributedCache而它对应的实现就是RedisCache那看下它的源码。这里就不细看所有的实现了重点只需要知道它继承了IDistributedCache就行了通过AddStackExchangeRedisCache传入的ConnectionString实现IDistributedCache的Get、Set、Refresh、Remove四个核心的方法我相信这难不倒你而它也就是干了这么多事情只不过它的实现有点巧妙。通过LUA脚本和HSET数据结构实现HashKey是我们传入的InstanceNamekey,做了一层包装。源码中还有需要注意的就是我们要保证Redis连接对象IConnectionMultiplexer的单例不能重复创建多个实例这个想必在RedisHelper中也是要保证的而且是通过lock来实现的。然而微软不是那么用的玩了个花样注意下面的_connectionLock.Wait();private readonly SemaphoreSlim _connectionLock new SemaphoreSlim(initialCount: 1, maxCount: 1);[MemberNotNull(nameof(_cache), nameof(_connection))]
private void Connect()
{CheckDisposed();if (_cache ! null){Debug.Assert(_connection ! null);return;}_connectionLock.Wait();try{if (_cache null){if (_options.ConnectionMultiplexerFactory null){if (_options.ConfigurationOptions is not null){_connection ConnectionMultiplexer.Connect(_options.ConfigurationOptions);}else{_connection ConnectionMultiplexer.Connect(_options.Configuration);}}else{_connection _options.ConnectionMultiplexerFactory().GetAwaiter().GetResult();}PrepareConnection();_cache _connection.GetDatabase();}}finally{_connectionLock.Release();}Debug.Assert(_connection ! null);
}通过SemaphoreSlim限制同一时间只能有一个线程能访问_connectionLock.Wait();后面的代码。学到装逼技巧1思考IDistributedCache只有四个操作Get、Set、Refresh、Remove我们表示很希望跟着官方走但这个接口过于简单不能满足我的其他需求咋办比如我们需要调用 StackExchange.Redis封装的LockTake,LockRelease来实现分布式锁的功能那该怎么通过注入IDistributedCache调用我们可以理解官方上面是给我们做了示范我们完全可以自己定义一个接口比如public interface IDistributedCachePlus : IDistributedCache
{bool LockRelease(string key, byte[] value);bool LockTake(string key, byte[] value, TimeSpan expiry);
}继承IDistributedCache对其接口进行增强然后自己实现实现AddStackExchangeRedisCache的逻辑我们不用官方给的实现但是我们山寨官方的思路实现任意标准的接口满足我们业务。services.Add(ServiceDescriptor.SingletonIDistributedCachePlus, RedisCachePlus());在需要使用缓存的地方通过构造函数注入IDistributedCachePlus。总结官方提供的IDistributedCache标准及其实现类库能方便的实现我们对缓存的简单的需求通过遵循官方的建议我们干掉了RedisHelper优雅的实现了分布式Redis缓存的使用你觉得这样做是不是很优雅呢