Ocelot一個優秀的.NET API網關框架
- 2021 年 1 月 14 日
- 筆記
- API Gateway, API網關, ASP.NET Core開發者指南, Ocelot
1 什麼是Ocelot?
Ocelot是一個用.NET Core實現並且開源的API網關,它功能強大,包括了:路由、請求聚合、服務發現、認證、鑒權、限流熔斷、並內置了負載均衡器與Service Fabric、Butterfly Tracing集成。
2 如何使用Ocelot?
首先,創建2個WebApi項目,WebApi01和WebApi02,地址分別//localhost:44313和//localhost:44390,其中WebApi01當作網關,WebApi02當作具體的微服務Api。
dotnet add package AutoMapper
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection
然後,將Ocelot的NuGet軟件包安裝到WebApi01項目中。
Ocelot
注意我這裡安裝的是17.0.0版本,配置方面會有點不一樣。
接着,在Startup.ConfigureServices中增加services.AddOcelot;
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Autofac.WebApi", Version = "v1" });
});
services.AddOcelot();
}
接着,在Startup.Configure中增加app.UseOcelot().Wait();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ocelot.WebApi01 v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseOcelot().Wait();
}
接着,創建ocelot.json文件
{
"Routes": [ //路由配置(注16.1版本將ReRoutes換成Routes)
{
"DownstreamPathTemplate": "/{url}", // 下游(服務提供方)服務路由模板
"DownstreamScheme": "https", // 下游Uri方案,http、https
"DownstreamHostAndPorts": [ // 服務地址和端口,如果是集群就設置多個
{
"Host": "localhost",
"Port": 44390
}
],
"UpstreamPathTemplate": "/api/{url}", // 上游(客戶端,服務消費方)請求路由模板
"UpstreamHttpMethod": [ "GET" ] // 允許的上游HTTP請求方法,可以寫多個
}
],
"GlobalConfiguration": { //全局配置
"BaseUrl": "//localhost:44313" //網關對外地址
}
}
最後,在Program.CreateHostBuilder中增加AddJsonFile(“ocelot.json”, optional: false, reloadOnChange: true);
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, builder) => {
builder.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Ok,讓我們來測試看看,//localhost:44313/api/WeatherForecast會不會跳轉//localhost:44390/WeatherForecast。