【.NET Core项目实战-统一认证平台】第五章 网关篇-自定义缓存Redis
【.net core项目实战-统一认证平台】开篇及目录索引
上篇文章我们介绍了2种网关配置信息更新的方法和扩展mysql存储,本篇我们将介绍如何使用redis来实现网关的所有缓存功能,用到的文档及源码将会在github上开源,每篇的源代码我将用分支的方式管理,本篇使用的分支为
course3
。
附文档及源码下载地址:[https://github.com/jinyancao/ctrauthplatform/tree/course3]
一、缓存介绍及选型
网关的一个重要的功能就是缓存,可以对一些不常更新的数据进行缓存,减少后端服务开销,默认ocelot
实现的缓存为本地文件进行缓存,无法达到生产环境大型应用的需求,而且不支持分布式环境部署,所以我们需要一个满足大型应用和分布式环境部署的缓存方案。redis应该是当前应用最广泛的缓存数据库,支持5种存储类型,满足不同应用的实现,且支持分布式部署等特性,所以缓存我们决定使用redis作为缓存实现。
本文将介绍使用csrediscore
来实现redis
相关操作,至于为什么选择csrediscore
,可参考文章[.net core开发者的福音之玩转redis的又一傻瓜式神器推荐],里面详细的介绍了各种redis组件比较及高级应用,并列出了不同组件的压力测试对比,另外也附csrediscore作者交流qq群:8578575
,使用中有什么问题可以直接咨询作者本人。
二、缓存扩展实现
首先本地安装redis
和管理工具redis desktop manager,本文不介绍安装过程,然后nuget
安装 csrediscore
,现在开始我们重写iocelotcache<t>
的实现,新建inrediscache.cs
文件。
using ctr.ahphocelot.configuration; using ocelot.cache; using system; using system.collections.generic; using system.text; namespace ctr.ahphocelot.cache { /// <summary> /// 金焰的世界 /// 2018-11-14 /// 使用redis重写缓存 /// </summary> /// <typeparam name="t"></typeparam> public class inrediscache<t> : iocelotcache<t> { private readonly ahphocelotconfiguration _options; public inrediscache(ahphocelotconfiguration options) { _options = options; csredis.csredisclient csredis; if (options.redisconnectionstrings.count == 1) { //普通模式 csredis = new csredis.csredisclient(options.redisconnectionstrings[0]); } else { //集群模式 //实现思路:根据key.gethashcode() % 节点总数量,确定连向的节点 //也可以自定义规则(第一个参数设置) csredis = new csredis.csredisclient(null, options.redisconnectionstrings.toarray()); } //初始化 redishelper redishelper.initialization(csredis); } /// <summary> /// 添加缓存信息 /// </summary> /// <param name="key">缓存的key</param> /// <param name="value">缓存的实体</param> /// <param name="ttl">过期时间</param> /// <param name="region">缓存所属分类,可以指定分类缓存过期</param> public void add(string key, t value, timespan ttl, string region) { key = getkey(region, key); if (ttl.totalmilliseconds <= 0) { return; } redishelper.set(key, value.tojson(), (int)ttl.totalseconds); } public void addanddelete(string key, t value, timespan ttl, string region) { add(key, value, ttl, region); } /// <summary> /// 批量移除regin开头的所有缓存记录 /// </summary> /// <param name="region">缓存分类</param> public void clearregion(string region) { //获取所有满足条件的key var data= redishelper.keys(_options.rediskeyprefix + "-" + region + "-*"); //批量删除 redishelper.del(data); } /// <summary> /// 获取执行的缓存信息 /// </summary> /// <param name="key">缓存key</param> /// <param name="region">缓存分类</param> /// <returns></returns> public t get(string key, string region) { key= getkey(region, key); var result = redishelper.get(key); if (!string.isnullorempty(result)) { return result.toobject<t>(); } return default(t); } /// <summary> /// 获取格式化后的key /// </summary> /// <param name="region">分类标识</param> /// <param name="key">key</param> /// <returns></returns> private string getkey(string region,string key) { return _options.rediskeyprefix + "-" + region + "-" + key; } } }
实现所有缓存相关接口,是不是很优雅呢?实现好缓存后,我们需要把我们现实的注入到网关里,在servicecollectionextensions
类中,修改注入方法。
/// <summary> /// 添加默认的注入方式,所有需要传入的参数都是用默认值 /// </summary> /// <param name="builder"></param> /// <returns></returns> public static iocelotbuilder addahphocelot(this iocelotbuilder builder, action<ahphocelotconfiguration> option) { builder.services.configure(option); //配置信息 builder.services.addsingleton( resolver => resolver.getrequiredservice<ioptions<ahphocelotconfiguration>>().value); //配置文件仓储注入 builder.services.addsingleton<ifileconfigurationrepository, sqlserverfileconfigurationrepository>(); //注册后端服务 builder.services.addhostedservice<dbconfigurationpoller>(); //使用redis重写缓存 builder.services.addsingleton<iocelotcache<fileconfiguration>, inrediscache<fileconfiguration>>(); builder.services.addsingleton<iocelotcache<cachedresponse>, inrediscache<cachedresponse>>(); return builder; }
奈斯,我们使用redis
实现缓存已经全部完成,现在开始我们在网关配置信息增加缓存来测试下,看缓存是否生效,并查看是否存储在redis
里。
为了验证缓存是否生效,修改测试服务api/values/{id}
代码,增加服务器时间输出。
[httpget("{id}")] public actionresult<string> get(int id) { return id+"-"+datetime.now.tostring("yyyy-mm-dd hh:mm:ss"); }
增加新的测试路由脚本,然后增加缓存策略,缓存60秒,缓存分类test_ahphocelot
。
--插入路由测试信息 insert into ahphreroute values(1,'/ctr/values/{id}','[ "get" ]','','http','/api/values/{id}','[{"host": "localhost","port": 9000 }]', '','','{ "ttlseconds": 60, "region": "test_ahphocelot" }','','','','',0,1); --插入网关关联表 insert into dbo.ahphconfigreroutes values(1,2);
现在我们测试访问网关地址http://localhost:7777/api/values/1
,过几十秒后继续访问,结果如下。
可以看出来,缓存已经生效,1分钟内请求都不会路由到服务端,再查询下redis缓存数据,发现缓存信息已经存在,然后使用redis desktop manager
查看redis缓存信息是否存在,奈斯,已经存在,说明已经达到我们预期目的。
三、解决网关集群配置信息变更问题
前面几篇已经介绍了网关的数据库存储,并介绍了网关的2种更新方式,但是如果网关集群部署时,采用接口更新方式,无法直接更新所有集群端配置数据,那如何实现集群配置信息一致呢?前面介绍了redis缓存,可以解决当前遇到的问题,我们需要重写内部配置文件提取仓储类,使用redis存储。
我们首先使用redis
实现iinternalconfigurationrepository
接口,每次请求配置信息时直接从redis存储,避免单机缓存出现数据无法更新的情况。redisinternalconfigurationrepository
代码如下。
using ctr.ahphocelot.configuration; using ocelot.configuration; using ocelot.configuration.repository; using ocelot.responses; using system; using system.collections.generic; using system.text; namespace ctr.ahphocelot.cache { /// <summary> /// 金焰的世界 /// 2018-11-14 /// 使用redis存储内部配置信息 /// </summary> public class redisinternalconfigurationrepository : iinternalconfigurationrepository { private readonly ahphocelotconfiguration _options; private iinternalconfiguration _internalconfiguration; public redisinternalconfigurationrepository(ahphocelotconfiguration options) { _options = options; csredis.csredisclient csredis; if (options.redisconnectionstrings.count == 1) { //普通模式 csredis = new csredis.csredisclient(options.redisconnectionstrings[0]); } else { //集群模式 //实现思路:根据key.gethashcode() % 节点总数量,确定连向的节点 //也可以自定义规则(第一个参数设置) csredis = new csredis.csredisclient(null, options.redisconnectionstrings.toarray()); } //初始化 redishelper redishelper.initialization(csredis); } /// <summary> /// 设置配置信息 /// </summary> /// <param name="internalconfiguration">配置信息</param> /// <returns></returns> public response addorreplace(iinternalconfiguration internalconfiguration) { var key = _options.rediskeyprefix + "-internalconfiguration"; redishelper.set(key, internalconfiguration.tojson()); return new okresponse(); } /// <summary> /// 从缓存中获取配置信息 /// </summary> /// <returns></returns> public response<iinternalconfiguration> get() { var key = _options.rediskeyprefix + "-internalconfiguration"; var result = redishelper.get<internalconfiguration>(key); if (result!=null) { return new okresponse<iinternalconfiguration>(result); } return new okresponse<iinternalconfiguration>(default(internalconfiguration)); } } }
redis实现后,然后在servicecollectionextensions
里增加接口实现注入。
builder.services.addsingleton<iinternalconfigurationrepository, redisinternalconfigurationrepository>();
然后启动网关测试,可以发现网关配置信息已经使用redis缓存了,可以解决集群部署后无法同步更新问题。
四、如何清除缓存记录
实际项目使用过程中,可能会遇到需要立即清除缓存数据,那如何实现从网关清除缓存数据呢?在上篇中我们介绍了接口更新网关配置的说明,缓存的更新也是使用接口的方式进行删除,详细代码如下。
using microsoft.aspnetcore.authorization; using microsoft.aspnetcore.mvc; namespace ocelot.cache { [authorize] [route("outputcache")] public class outputcachecontroller : controller { private readonly iocelotcache<cachedresponse> _cache; public outputcachecontroller(iocelotcache<cachedresponse> cache) { _cache = cache; } [httpdelete] [route("{region}")] public iactionresult delete(string region) { _cache.clearregion(region); return new nocontentresult(); } } }
我们可以先拉去授权,获取授权方式请参考上一篇,然后使用http delete
方式,请求删除地址,比如删除前面的测试缓存接口,可以请求http://localhost:7777/ctrocelot/outputcache/test_ahphocelot
地址进行删除,可以使用postman
进行测试,测试结果如下。
执行成功后可以删除指定的缓存记录,且立即生效,完美的解决了我们问题。
五、总结及预告
本篇我们介绍了使用redis缓存来重写网关的所有缓存模块,并把网关配置信息也存储到redis里,来解决集群部署的问题,如果想清理缓存数据,通过网关指定的授权接口即可完成,完全具备了网关的缓存的相关模块的需求。
下一篇开始我们开始介绍针对不同客户端设置不同的权限来实现自定义认证,敬请期待,后面的课程会越来越精彩,也希望大家多多支持。
上一篇: 呆子待客
推荐阅读
-
【.NET Core项目实战-统一认证平台】第二章网关篇-重构Ocelot来满足需求
-
【.NET Core项目实战-统一认证平台】第十六章 网关篇-Ocelot集成RPC服务
-
【.NET Core项目实战-统一认证平台】第九章 授权篇-使用Dapper持久化IdentityServer4
-
【.NET Core项目实战-统一认证平台】第十二章 授权篇-深入理解JWT生成及验证流程
-
【.NET Core项目实战-统一认证平台】第三章 网关篇-数据库存储配置(1)
-
【.NET Core项目实战-统一认证平台】第六章 网关篇-自定义客户端授权
-
【.NET Core项目实战-统一认证平台】第十三章 授权篇-如何强制有效令牌过期
-
【.NET Core项目实战-统一认证平台】第十四章 授权篇-自定义授权方式
-
【.NET Core项目实战-统一认证平台】第十五章 网关篇-使用二级缓存提升性能
-
【.NET Core项目实战-统一认证平台】第十章 授权篇-客户端授权