Ocelot中使用 CacheManager 来支持缓存,官方文档中强烈建议使用该包作为缓存工具。
以下介绍通过使用CacheManager来实现Ocelot缓存。

1、通过Nuget添加 Ocelot.Cache.CacheManager 包

在OcelotGetway项目中添加引用:

2、修改 Startup 中的 ConfigureServices 方法

修改如下:

services    .AddOcelot(new ConfigurationBuilder()    .AddJsonFile("configuration.json")          .Build())    .AddConsul()    .AddCacheManager(x => x.WithDictionaryHandle())    .AddAdministration("/administration", "secret");

3、修改 WebApiA 添加一个 TimeController 并添加如下代码:

using System;using Microsoft.AspNetCore.Mvc;

namespace WebApiA.Controllers{    [Produces("application/json")]    [Route("api/[controller]/[action]")]public class TimeController : Controller    {        [HttpGet]public string GetNow(){return DateTime.Now.ToString("hh:mm:ss");        }    }}

启动WebApiA项目并使用Postman多次请求 http://localhost:5000/api/Time/GetNow

可以看到每次返回的时间不同。

4、修改OcelotGetway项目中的 configuration.json,在 ReRoutes 中添加如下配置:

{"DownstreamPathTemplate": "/api/Time/GetNow","DownstreamScheme": "http","DownstreamHostAndPorts": [      {"Host": "localhost","Port": 5001      }    ],"UpstreamPathTemplate": "/Now","UpstreamHttpMethod": [ "Get" ],"FileCacheOptions": {"TtlSeconds": 60,"Region": "somename"    }}

对 FileCacheOptions 配置做下解释:

  • TtlSeconds: 缓存时间(秒)

  • Region: 缓存区,表示改配置缓存放到哪个区域,可以在配置管理中进行维护,后边将做详细介绍
    用一句话解释改配置:对链接http://localhost:5000/Now使用somename缓存区进行60秒缓存。
    然后启动OcelotGetway项目,使用Postman请求如下:

    多次请求在一分钟之内得到的返回数据并未发生变化。
    至此,缓存配置完成。

5、使用配置管理清除缓存

在配置管理篇中并没有介绍清除缓存api的使用,而是留到了本片来进行介绍。要使用配置管理需要先按照之前的文章进行配置。
以下介绍清除缓存的方法。
使用Postman post请求http://localhost:5000/administration/connect/token如下:

得到token。

使用Postman delete请求

http://localhost:5000/administration/outputcache/somename

并bearer上述得到的token如下:

delete somename token.png

再次请求

http://localhost:5000/Now

,可以发现与上次请求的返回时间不同。

注意:两次请求http://localhost:5000/Now的时间间隔要控制在60s之内才能看出效果。

6、实现自己的缓存

Ocelot提供了接口可以让我们自己实现缓存处理类,该类要实现 IOcelotCache<CachedResponse>,并且要在 Startup中的 ConfigureServices 方法中的 AddOcelot 之后添加 services.AddSingleton<IOcelotCache<CachedResponse>, MyCache>(); 来注入自己的缓存处理类覆盖Ocelot中默认的缓存处理。
如果需要实现文件缓存需要实现 IOcelotCache<FileConfiguration> 接口并添加相应注入。
提供一个简单版本的缓存处理类(非常不建议生产环境使用):

using System;using System.Collections.Generic;using System.Linq;using Ocelot.Cache;

namespace OcelotGetway{public class MyCache : IOcelotCache<CachedResponse>    {private static Dictionary<string, CacheObj> _cacheObjs = new Dictionary<string, CacheObj>();

public void Add(string key, CachedResponse value, TimeSpan ttl, string region){if (!_cacheObjs.ContainsKey($"{region}_{key}"))            {                _cacheObjs.Add($"{region}_{key}", new CacheObj()                {                    ExpireTime = DateTime.Now.Add(ttl),                    Response = value                });            }        }

public CachedResponse Get(string key, string region){if (!_cacheObjs.ContainsKey($"{region}_{key}")) return null;

            var cacheObj = _cacheObjs[$"{region}_{key}"];if (cacheObj != null && cacheObj.ExpireTime >= DateTime.Now)            {return cacheObj.Response;            }

            _cacheObjs.Remove($"{region}_{key}");return null;

        }

public void ClearRegion(string region){            var keysToRemove = _cacheObjs.Where(c => c.Key.StartsWith($"{region}_"))                .Select(c => c.Key)                .ToList();            foreach (var key in keysToRemove)            {                _cacheObjs.Remove(key);            }

        }

public void AddAndDelete(string key, CachedResponse value, TimeSpan ttl, string region){if (_cacheObjs.ContainsKey($"{region}_{key}"))            {                _cacheObjs.Remove($"{region}_{key}");            }

            _cacheObjs.Add($"{region}_{key}", new CacheObj()            {                ExpireTime = DateTime.Now.Add(ttl),                Response = value            });        }    }

public class CacheObj    {public DateTime ExpireTime { get; set; }

public CachedResponse Response { get; set; }    }}

源码下载 https://github.com/Weidaicheng/OcelotTutorial/tree/%E6%95%99%E7%A8%8B%EF%BC%888%EF%BC%89

完,下一篇介绍QoS

相关文章:

  • .Netcore 2.0 Ocelot Api网关教程(番外篇)- Ocelot v13.x升级

  • .Netcore 2.0 Ocelot Api网关教程(6)- 配置管理

  • .Netcore 2.0 Ocelot Api网关教程(7)- 限流

  • 【.NET Core项目实战-统一认证平台】第十六章 网关篇-Ocelot集成RPC服务

  • ocelot 自定义认证和授权

  • eShopOnContainers 知多少[9]:Ocelot gateways

  • 使用Ocelot、IdentityServer4、Spring Cloud Eureka搭建微服务网关:(一)

原文地址:https://www.jianshu.com/p/5034384a8e61

.NET社区新闻,深度好文,欢迎访问公众号文章汇总 http://www.csharpkit.com

.Netcore 2.0 Ocelot Api网关教程(8)- 缓存相关推荐

  1. .Netcore 2.0 Ocelot Api网关教程(7)- 限流

    本文介绍Ocelot中的限流,限流允许Api网关控制一段时间内特定api的总访问次数. 限流的使用非常简单,只需要添加配置即可. 1.添加限流 修改 configuration.json 配置文件,对 ...

  2. .Netcore 2.0 Ocelot Api网关教程(6)- 配置管理

    本文介绍Ocelot中的配置管理,配置管理允许在Api网关运行时动态通过Http Api查看/修改当前配置.由于该功能权限很高,所以需要授权才能进行相关操作.有两种方式来认证,外部Identity S ...

  3. .Netcore 2.0 Ocelot Api网关教程(番外篇)- Ocelot v13.x升级

    由于Ocelot系列博客好久没更新(差不多有10个月的时间了),在此先说声抱歉,Ocelot系列会继续更新下去. 在写上一篇配置管理的时候发现官方文档已经和以前的不一样,而Ocelot也从5.0版本更 ...

  4. Ocelot Api网关教程(9)- QoS

    本文介绍Ocelot中的QoS(Quality of Service),其使用了Polly对超时等请求下游失败等情况进行熔断. 1.添加Nuget包 添加 Ocelot.Provider.Polly  ...

  5. Angular SPA基于Ocelot API网关与IdentityServer4的身份认证与授权

    在上一讲中,我们已经完成了一个完整的案例,在这个案例中,我们可以通过Angular单页面应用(SPA)进行登录,然后通过后端的Ocelot API网关整合IdentityServer4完成身份认证.在 ...

  6. ASP.NET Core on K8s学习之旅(13)Ocelot API网关接入

    [云原生]| 作者/Edison Zhou 这是恰童鞋骚年的第232篇原创文章 上一篇介绍了Ingress的基本概念和Nginx Ingress的基本配置和使用,考虑到很多团队都在使用Ocelot作为 ...

  7. Angular SPA基于Ocelot API网关与IdentityServer4的身份认证与授权(三)

    在前面两篇文章中,我介绍了基于IdentityServer4的一个Identity Service的实现,并且实现了一个Weather API和基于Ocelot的API网关,然后实现了通过Ocelot ...

  8. Angular SPA基于Ocelot API网关与IdentityServer4的身份认证与授权(一)

    好吧,这个题目我也想了很久,不知道如何用最简单的几个字来概括这篇文章,原本打算取名<Angular单页面应用基于Ocelot API网关与IdentityServer4+ASP.NET Iden ...

  9. .Net Core微服务入门——Ocelot API网关接入(二)

    Net Core微服务入门--Ocelot API网关接入(二) 我们先接入Consul,实现服务发现 服务发现 1.引入 Ocelot.Provider.Consul 包 2.修改ocelot.js ...

最新文章

  1. matlab最小分类错误全局二值化算法
  2. Win10怎么设置虚拟内存?
  3. [转]史上最全的后端技术大全,你都了解哪些技术呢?
  4. CF704B. Ant Man
  5. 关于msbuild 编译.net 4.5新语法错误的解决方法
  6. html5干货,干货:详解HTML5中常见的五大全局属性
  7. Java核心(一)线程Thread详解
  8. 2.7 Inception 网络
  9. python进阶07并发之三其他问题
  10. C++算法学习(力扣:328. 奇偶链表)
  11. python仿360界面_高仿360界面的实现(用纯XML和脚本实现)
  12. ubuntu如何打拼音
  13. b85主板装服务器系统,[U盘装系统]技嘉B85主板U盘装系统图文教程
  14. html添加到购物车飞入动画效果,加入购物车的动画效果
  15. 极客时间马哥教育-云原生训练营第一周作业-20221016
  16. 枢纽披红彩车上路 申城公交传递城市年味
  17. 10个我经常逛的“小网站”,嘿嘿嘿
  18. 清除 柯美367打印机 转印辊组件、碳粉过滤器和臭氧过滤器报警
  19. 【历史上的今天】3 月 7 日:首条海底光缆开通;VeriSign 收购 Network Solutions;计算机图形学先驱诞生
  20. 转 Java知识——精华总结

热门文章

  1. imessage_如何在所有Apple设备上同步您的iMessage
  2. sizeof string
  3. 【tomcat】servlet原理及其生命周期
  4. 016-Spring Boot JDBC
  5. Nginx图片剪裁模块探究 http_image_filter_module
  6. css 中图片旋转,倾斜,位移,平滑
  7. npm执行命令后无任何响应(windows下)
  8. WSUS专题之二:部署与规划1
  9. .NET跨平台实践:.NetCore、.Net5/6 Linux守护进程设计
  10. C#开源类库推荐:拼多多开放平台SDK,开源免费,支持.NET Core!