温州育英国际实验学校,凌云网,重生金蝉子
本来昨天应该更新的,但是由于各种原因,抱歉,让追这个系列的朋友久等了。上一篇文章 在.net core 使用缓存和配置依赖策略 讲的是如何使用本地缓存,那么本篇文章就来了解一下如何使用分布式缓存,通过本章,你将了解到如何使用分布式缓存,以及最重要的是,如何选择适合自己的分布式缓存;本章主要包含两个部分:
内容提要
- 使用 sqlserver 分布式缓存
- 使用 redis 分布式缓存
- 实现自定义的分布式缓存客户端注册扩展
- 关于本示例的使用说明
dotnet sql-cache create "server=.\sqlexpress;user=sa;password=123456;database=testdb" dbo aspnetcorecache
.net core 中的分布式缓存统一接口是 idistributedcache 该接口定义了一些对缓存常用的操作,比如我们常见的 set/get 方法,而 sqlserver 分布式缓存由 sqlservercache 类实现,该类位于命名空间 microsoft.extensions.caching.sqlserver 中
public void configureservices(iservicecollection services) { services.adddistributedsqlservercache(options => { options.systemclock = new bll.localsystemclock(); options.connectionstring = this.configuration["connectionstring"]; options.schemaname = "dbo"; options.tablename = "aspnetcorecache"; options.defaultslidingexpiration = timespan.fromminutes(1); options.expireditemsdeletioninterval = timespan.fromminutes(5); }); ... }
上面的方法 configureservices(iservicecollection services) 中使用 services.adddistributedsqlservercache() 这个扩展方法引入了 sqlserver 分布式缓存,并作了一些简单的配置,该配置是由 sqlservercacheoptions 决定的,sqlservercacheoptions 的配置非常重要,这里强烈建议大家手动配置
namespace microsoft.extensions.caching.sqlserver { public class sqlservercacheoptions : ioptions<sqlservercacheoptions> { public sqlservercacheoptions(); // 缓存过期扫描时钟 public isystemclock systemclock { get; set; } // 缓存过期逐出时间,默认为 30 分钟 public timespan? expireditemsdeletioninterval { get; set; } // 缓存数据库连接字符串 public string connectionstring { get; set; } // 缓存表所属架构 public string schemaname { get; set; } // 缓存表名称 public string tablename { get; set; } // 缓存默认过期时间,默认为 20 分钟 public timespan defaultslidingexpiration { get; set; } } }
该配置非常简单,仅是对缓存使用的基本配置
首先,使用 options.systemclock 配置了一个本地时钟,接着设置缓存过期时间为 1 分钟,缓存过期后逐出时间为 5 分钟,其它则是连接数据库的各项配置
在缓存过期扫描的时候,使用的时间正是 options.systemclock 该时钟的时间,默认情况下,该时钟使用 utc 时间,在我的电脑上,utc 时间是得到的是美国时间,所以这里实现了一个本地时钟,代码非常简单,只是获取一个本地时间
public class localsystemclock : microsoft.extensions.internal.isystemclock { public datetimeoffset utcnow => datetime.now; }
[route("api/home")] [apicontroller] public class homecontroller : controller { private idistributedcache cache; public homecontroller(idistributedcache cache) { this.cache = cache; } [httpget("index")] public async task<actionresult<string>> settime() { var currenttime = datetime.now.tostring(); await this.cache.setstringasync("currenttime", currenttime); return currenttime; } [httpget("gettime")] public async task<actionresult<string>> gettime() { var currenttime = await this.cache.getstringasync("currenttime"); return currenttime; } }
在缓存过期后,每次调用 get/getasync 方法都会 调用 sqlservercache 的 私有方法 scanforexpireditemsifrequired() 进行一次扫描,然后清除所有过期的缓存条目,扫描方法执行过程也很简单,就是直接执行数据库查询语句
delete from {0} where @utcnow > expiresattime
值得注意的是,在异步方法中使用同步调用不会触发缓存逐出,因为其线程退出导致 task.run 未能运行,比如下面的代码
[httpget("gettime")] public async task<actionresult<string>> gettime() { var currenttime = this.cache.getstring("currenttime"); return currenttime; }
将导致 sqlservercache 无法完整执行方法 scanforexpireditemsifrequired(),因为其内部使用了 task 进行异步处理,正确的做法是使用 await this.cache.getstringasync("currenttime");
private void scanforexpireditemsifrequired() { var utcnow = _systemclock.utcnow; if ((utcnow - _lastexpirationscan) > _expireditemsdeletioninterval) { _lastexpirationscan = utcnow; task.run(_deleteexpiredcacheditemsdelegate); } }
在多线程环境下,该方法可能除非多次重复扫描,即可能会多次执行 sql 语句 delete from {0} where @utcnow > expiresattime ,但是,这也仅仅是警告而已,并没有任何可改变其行为的控制途径
.net core 中还对 idistributedcache 进行了扩展,甚至允许通过 set 方法传入一个 distributedcacheentryoptions 以覆盖全局设置,这些扩展方法的使用都比较简单,直接传入相应的值即可,在此不再一一介绍
希望深入研究的同学,可以手动逐一测试
adddistributedsqlservercache 方法内部实际上是进行了一系列的注册操作,其中最重要的是注册了 sqlservercache 到 idistributedcache 接口,该操作使得我们可以在控制器中采用依赖注入的方式使用 idistributedcache 的实例
查看 adddistributedsqlservercache 方法的代码片段
public static iservicecollection adddistributedsqlservercache(this iservicecollection services, action<sqlservercacheoptions> setupaction) { if (services == null) { throw new argumentnullexception(nameof(services)); } if (setupaction == null) { throw new argumentnullexception(nameof(setupaction)); } services.addoptions(); addsqlservercacheservices(services); services.configure(setupaction); return services; } internal static void addsqlservercacheservices(iservicecollection services) { services.add(servicedescriptor.singleton<idistributedcache, sqlservercache>()); }
要在 asp.net core 项目中使用 redis 分布式缓存,需要引用包:microsoft.extensions.caching.redis,.net core 中的 redis 分布式缓存客户端由 rediscache 类提供实现 ,rediscache 位于程序集 microsoft.extensions.caching.stackexchangeredis.dll 中,该程序集正是是依赖于大名鼎鼎的 redis 客户端 stackexchange.redis.dll,stackexchange.redis 有许多的问题,其中最为严重的是超时问题,不过这不知本文的讨论范围,如果你希望使用第三方 redis 客户端替代 stackexchange.redis 来使用分布式缓存,你需要自己实现 idistributedcache 接口,好消息是,idistributedcache 接口并不复杂,定义非常简单
public void configureservices(iservicecollection services) { services.adddistributedrediscache(options => { options.instancename = "testdb"; options.configuration = this.configuration["redisconnectionstring"]; }); ... }
注册 redis 分布式缓存配置和使用 stackexchange.redis 的方式完全相同,需要注意的是 rediscacheoptions 包含 3 个属性,而 configuration 和 configurationoptions 的作用是相同的,一旦设置了 configurationoptions ,就不应该再去设置属性 configuration 的值,因为,在 adddistributedrediscache() 注册内部,会判断如果设置了 configurationoptions 的值,则不再使用 configuration;但是,我们建议还是通过属性 configuration 去初始化 redis 客户端,因为,这是一个连接字符串,而各种配置都可以通过连接字符串进行设置,这和使用 stackexchange.redis 的方式是完全一致的
[route("api/home")] [apicontroller] public class homecontroller : controller { private idistributedcache cache; public homecontroller(idistributedcache cache) { this.cache = cache; } [httpget("index")] public async task<actionresult<string>> settime() { var currenttime = datetime.now.tostring(); await this.cache.setstringasync("currenttime", currenttime); return currenttime; } [httpget("gettime")] public async task<actionresult<string>> gettime() { var currenttime = await this.cache.getstringasync("currenttime"); return currenttime; } }
细心的你可能已经发现了,上面的这段代码和之前演示的 sqlservercache 完全一致,是的,仅仅是修改一下注册的方法,我们就能在项目中进行无缝的切换;但是,对于缓存有强依赖的业务,建议还是需要做好缓存迁移,确保项目能够平滑过渡
唯一不同的是,使用 redis 分布式缓存允许你在异步方法中调用同步获取缓存的方法,这不会导致缓存清理的问题,因为缓存的管理已经完全交给了 redis 客户端 stackexchange.redis 了
public class csrediscache : idistributedcache, idisposable { private csredis.csredisclient client; private csredisclientoptions _options; public csrediscache(ioptions<csredisclientoptions> optionsaccessor) { if (optionsaccessor == null) { throw new argumentnullexception(nameof(optionsaccessor)); } _options = optionsaccessor.value; if (_options.noderule != null && _options.connectionstrings != null) client = new csredis.csredisclient(_options.noderule, _options.connectionstrings); else if (_options.connectionstring != null) client = new csredis.csredisclient(_options.connectionstring); else throw new argumentnullexception(nameof(_options.connectionstring)); redishelper.initialization(client); } public void dispose() { if (client != null) client.dispose(); } public byte[] get(string key) { if (key == null) { throw new argumentnullexception(nameof(key)); } return redishelper.get<byte[]>(key); } public async task<byte[]> getasync(string key, cancellationtoken token = default(cancellationtoken)) { if (key == null) { throw new argumentnullexception(nameof(key)); } token.throwifcancellationrequested(); return await redishelper.getasync<byte[]>(key); } public void refresh(string key) { throw new notimplementedexception(); } public task refreshasync(string key, cancellationtoken token = default(cancellationtoken)) { throw new notimplementedexception(); } public void remove(string key) { if (key == null) { throw new argumentnullexception(nameof(key)); } redishelper.del(key); } public async task removeasync(string key, cancellationtoken token = default(cancellationtoken)) { if (key == null) { throw new argumentnullexception(nameof(key)); } await redishelper.delasync(key); } public void set(string key, byte[] value, distributedcacheentryoptions options) { if (key == null) { throw new argumentnullexception(nameof(key)); } redishelper.set(key, value); } public async task setasync(string key, byte[] value, distributedcacheentryoptions options, cancellationtoken token = default(cancellationtoken)) { if (key == null) { throw new argumentnullexception(nameof(key)); } await redishelper.setasync(key, value); } }
代码不多,都是实现 idistributedcache 接口,然后在 idisposable.dispose 中释放资源
public class csredisclientoptions { public string connectionstring { get; set; } public func<string, string> noderule { get; set; } public string[] connectionstrings { get; set; } }
该配置类主要是为 csredis 客户端接收配置使用
public static class csrediscacheservicecollectionextensions { public static iservicecollection addcsrediscache(this iservicecollection services, action<csredisclientoptions> setupaction) { if (services == null) { throw new argumentnullexception(nameof(services)); } if (setupaction == null) { throw new argumentnullexception(nameof(setupaction)); } services.addoptions(); services.configure(setupaction); services.add(servicedescriptor.singleton<idistributedcache, csrediscache>()); return services; } }
自定义一个扩展方法,进行配置初始化工作,简化实际注册使用时的处理步骤
public void configureservices(iservicecollection services) { services.addcsrediscache(options => { options.connectionstring = this.configuration["redisconnectionstring"]; }); ... }
上面的代码就简单实现了一个第三方分布式缓存客户端的注册和使用
[route("api/customer")] [apicontroller] public class customercontroller : controller { private idistributedcache cache; public customercontroller(idistributedcache cache) { this.cache = cache; } [httpget("newid")] public async task<actionresult<string>> newid() { var id = guid.newguid().tostring("n"); await this.cache.setstringasync("customerid", id); return id; } [httpget("getid")] public async task<actionresult<string>> getid() { var id = await this.cache.getstringasync("customerid"); return id; } }
该控制器简单实现两个接口,newid/getid,运行程序,输出结果正常
至此,我们完整的实现了一个自定义分布式缓存客户端注册
该解决方案红框处定义了 3 个不同的 startup.cs 文件,分别是
- csredisstartup (自定义缓存测试启动文件)
- sql_startup (sqlserver 测试启动文件)
- stackchangeredis_startup(stackchange.redis 测试启动文件)
public static iwebhostbuilder createwebhostbuilder(string[] args) => webhost.createdefaultbuilder(args) .usestartup<ron.distributedcachedemo.startups.sqlserver.startup>();
通过介绍,我们了解到如何在 asp.net core 中使用分布式缓存
了解了使用不同的缓存类型,如 sqlserver 和 redis
了解到了如何使用不同的缓存类型客户端进行注册
了解到如何实现自定义缓存客户端
还知道了在调用 sqlserver 缓存的时候,异步方法中的同步调用会导致 sqlservercache 无法进行过期扫描
csrediscore 此项目是由我的好朋友 维护,github 仓库地址:访问csrediscore
https://files.cnblogs.com/files/viter/ron.distributedcachedemo.zip
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论