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

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

在OcelotGetway项目中添加引用:

 
Add cache package.png

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

 
Now1.png
 
Now2.png

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

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请求如下:
     
    Now from cache.gif

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

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

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

 
get token.png

得到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; }
}
}

源码下载

完,下一篇介绍QoS

 
 

5人点赞

 
Ocelot

 
 

作者:Weidaicheng
链接:https://www.jianshu.com/p/5034384a8e61
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

.Netcore 2.0 Ocelot Api网关教程(8)- 缓存的更多相关文章

  1. .Netcore 2.0 Ocelot Api网关教程(2)- 路由

    .Netcore 2.0 Ocelot Api网关教程(1) 路由介绍 上一篇文章搭建了一个简单的Api网关,可以实现简单的Api路由,本文介绍一下路由,即配置文件中ReRoutes,ReRoutes ...

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

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

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

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

  4. .Netcore 2.0 Ocelot Api网关教程(5)- 认证和授权

    本文介绍Ocelot中的认证和授权(通过IdentityServer4),本文只使用最简单的IdentityServer,不会对IdentityServer4进行过多讲解. 1.Identity Se ...

  5. .Netcore 2.0 Ocelot Api网关教程(1)- 入门

    Ocelot(Github)Ocelot官方文档(英文)本文不会介绍Api网关是什么以及Ocelot能干什么需要对Api网关及Ocelot有一定的理论了解 开始使用Ocelot搭建一个入门级Api网关 ...

  6. .Netcore 2.0 Ocelot Api网关教程(10)- Headers Transformation

    本文介绍Ocelot中的请求头传递(Headers Transformation),其可以改变上游request传递给下游/下游response传递给上游的header. 1.修改ValuesCont ...

  7. .Netcore 2.0 Ocelot Api网关教程(9)- QoS

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

  8. .Netcore 2.0 Ocelot Api网关教程(4)- 服务发现

    本文介绍Ocelot中的服务发现(Service Discovery),Ocelot允许指定一个服务发现提供器,之后将从中寻找下游服务的host和port来进行请求路由.关于服务发现的详细介绍请点击. ...

  9. .Netcore 2.0 Ocelot Api网关教程(3)- 路由聚合

    在实际的应用当中,经常会遇到同一个操作要请求多个api来执行.这里先假设一个应用场景:通过姓名获取一个人的个人信息(性别.年龄),而获取每种个人信息都要调用不同的api,难道要依次调用吗?在Ocelo ...

随机推荐

  1. CSRF(cross-site request forgery )跨站请求攻击

    CSRF(cross-site request forgery )跨站请求伪造,攻击者盗用了你的身份,以你的名义发送恶意请求,对服务器来说这个请求是完全合法的,但是却完成了攻击者所期望的一个操作,通过 ...

  2. Java : 对象不再使用时,为什么要赋值为 null ?

    今天遇到一个比较有意思的问题,对象不再使用时,为什么要赋值为 null ? 在这里我看到一篇文章说的不错,下面是网址,有兴趣的IT友可以看看. https://mp.weixin.qq.com/s/Z ...

  3. JS window对象详解

    window 是客户端浏览器对象模型的基类,window 对象是客户端 JavaScript 的全局对象.一个 window 对象实际上就是一个独立的窗口,对于框架页面来说,浏览器窗口每个框架都包含一 ...

  4. C# 任务、线程、同步(五)

    1.数据流使用  TPL Data Flow 类库 class Program { static void Main(string[] args) { // ActionBlock(); // Sou ...

  5. BZOJ 1778: [Usaco2010 Hol]Dotp 驱逐猪猡 (高斯消元)

    题面 题目传送门 分析 令爆炸概率为PPP.设 f(i)=∑k=0∞pk(i)\large f(i)=\sum_{k=0}^{\infty}p_k(i)f(i)=∑k=0∞​pk​(i),pk(i)p ...

  6. js.map文件意义(转)

    什么是source map文件 source map文件是js文件压缩后,文件的变量名替换对应.变量所在位置等元信息数据文件,一般这种文件和min.js主文件放在同一个目录下. 比如压缩后原变量是ma ...

  7. 037_自动添加防火墙规则,开启某些服务或端口(适用于 RHEL7)

    #!/bin/bash#设置变量定义需要添加到防火墙规则的服务和端口号#使用 firewall-cmd --get-services 可以查看 firewall 支持哪些服务 service=&quo ...

  8. tinymce实现ctrl+v粘贴word图片并上传

    tinymce是很优秀的一款富文本编辑器,可以去官网下载.https://www.tiny.cloud 这里分享的是它官网的一个收费插件powerpaste的旧版本源码,但也不影响功能使用. http ...

  9. APIO2009 抢掠计划 Tarjan DAG-DP

    APIO2009 抢掠计划 Tarjan spfa/DAG-DP 题面 一道\(Tarjan\)缩点水题.因为可以反复经过节点,所以把一个联通快中的所有路口看做一个整体,缩点后直接跑\(spfa\)或 ...

  10. skb head/data/tail/end/介绍

    2017年04月26日 18:21:12 abcLinux 阅读数 799   This first diagram illustrates the layoutof the SKB data are ...