.Netcore 2.0 Ocelot Api网关教程(8)- 缓存
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.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)- 缓存的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序员修神之路--
- 下一篇: .NET Core 给使用.NET的公司