前言
Ocelot是一個基於中間件的網關實現,功能有很多。從淺入深簡單學習並記錄一下吧。本篇就是一個簡單的路由配置實現。
DEMO 搭建
首先建立三個項目。Api.User,Api.Article,Api.GateWay.ApiGateWay項目中引入Ocelot Nuget包.添加配置文件Ocelot.json.
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/{all}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 60001
}
],
"UpstreamPathTemplate": "/user/{all}",
"UpstreamHttpMethod": ["GET","POST"]
},
{
"DownstreamPathTemplate": "/{all}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 60002
}
],
"UpstreamPathTemplate": "/article/{all}",
"UpstreamHttpMethod": ["GET","POST"]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:60003/"
}
}
啟動的時候將配置文件加進去,並且Startup中添加相應的中間件:services.AddOcelot(),app.UseOcelot();
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("ocelot.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
}).UseStartup<Startup>();
啟動三個項目,運行效果如下:

總結
這樣就能實現將網關做為統一入口,統一管理了。后續在加上各種Ocelot的功能實現。
