ASP-NET Core Api 網關 Ocelot 初探
概述
Ocelot 面向使用. NET 運行微型服務 / 面向服務的體系結構的人員,這些體系結構需要在系統中具有統一的入口點。特別是我想與 IdentityServer 參考和承載令牌輕鬆集成。Ocelot 是按特定順序排列的一堆中間件。Ocelot 將 HttpRequest 對象操作到由其配置指定的狀態,直到到達請求構建器中間件,在該中間件中它創建一個 HttpRequestMessage 對象,該對象用於向下遊服務發出請求。發出請求的中間件是 Ocelot 管道中的最後一件事。它不會調用下一個中間件。有一塊中間件可將 HttpResponseMessage 映射到 HttpResponse 對象,然後將其返回給客戶端。基本上,它具有許多其他功能。
代碼實現
1、新建 api 客戶端 1
2、新建 api 網關 test
3、nuget 安裝 Ocelot
4、Program 文件添加 ConfigureAppConfiguration
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(conf =>
{
conf.AddJsonFile("ocelot.json", false, true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
5、Startup 文件配置
services.AddOcelot(Configuration);
app.UseOcelot().Wait();
6、網關項目下添加文件 ocelot.json
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/WeatherForecast/GetList",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5000
}
],
"UpstreamPathTemplate": "/GetList",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5000
}
],
"UpstreamPathTemplate": "/{everything}",
"UpstreamHttpMethod": [ "Post" ]
},
{
"DownstreamPathTemplate": "/api/WeatherForecast/GetModel?id={s1}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5000
}
],
"UpstreamPathTemplate": "/GetModel?id={s1}",
"UpstreamHttpMethod": [ "Get" ]
}
]
}
7、2 個項目運行,測試
代碼地址
https://gitee.com/conanOpenSource_admin/Example/commit/b3b5a6b15a060b46c5ecd2ea31f0d36791cda18c
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/iXbmwb529ugiqx0euZbnIQ