大神張善友 分享過一篇 《.NET Core 在騰訊財付通的企業級應用開發實踐》裡面就是用.net core 和 Ocelot搭建的可擴展的高性能Api網關。 Ocelot(http://ocelot.readthedocs.io)是一個用.NET Core實現並且開源的API網關,它功能強大,包括 ...
大神張善友 分享過一篇 《.NET Core 在騰訊財付通的企業級應用開發實踐》裡面就是用.net core 和 Ocelot搭建的可擴展的高性能Api網關。
Ocelot(http://ocelot.readthedocs.io)是一個用.NET Core實現並且開源的API網關,它功能強大,包括了:路由、負載均衡、請求聚合、認證、鑒權、限流熔斷等,這些功能只都只需要簡單的配置即可完成。
Consul(https://www.consul.io)是一個分散式,高可用、支持多數據中心的服務註冊、發現、健康檢查和配置共用的服務軟體,由 HashiCorp 公司用 Go 語言開發。
Ocelot天生集成對Consul支持,在OcelotGateway項目中Ocelot.json配置就可以開啟ocelot+consul的組合使用,實現服務註冊、服務發現、健康檢查、負載均衡。
軟體版本
Asp.net Core:2.0
Ocelot:7.1.0-unstable0011(開發時最新)
Consul:1.1.0(開發時最新)
本文分開兩部分:1、基於Ocelot搭建Api網關;2、Ocelot+Consul 實現下游服務的服務註冊、服務發現、健康檢查、負載均衡。
項目結構
Snai.Ocelot 網關:
Snai.ApiGateway Asp.net Core 2.0 Api網關
Snai.ApiServiceA Asp.net Core 2.0 Api下游服務A
Snai.ApiServiceB Asp.net Core 2.0 Api下游服務B
ApiServiceA和ApiServiceB其實是一樣的,用於負載,為了測試方便,我建了兩個項目
Consul:
conf 配置目錄
data 緩存數據目錄
dist Consul UI目錄
consul.exe 註冊軟體
startup.bat 執行腳本
項目實現
一、基於Ocelot搭建Api網關
新建Snai.Ocelot解決方案
1、搭建Api網關
新建 Snai.ApiGateway 基於Asp.net Core 2.0空網站,在 依賴項 右擊 管理NuGet程式包 瀏覽 找到 Ocelot 版本7.1.0-unstable0011安裝
1.1、在項目根目錄下新建一個 Ocelot.json 文件,打開 Ocelot.json 文件,配置Ocelot參數,Ocelot.json 代碼如下
{
"ReRoutes": [
{
"UpstreamPathTemplate": "/apiservice/{controller}",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/apiservice/{controller}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"host": "localhost",
"port": 5011
},
{
"host": "localhost",
"port": 5012
}
],
"LoadBalancerOptions": {
"Type": "LeastConnection"
}
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000"
}
}
如果有多個下游服務,把ReRoutes下 {...} 複製多份,最終如: "ReRoutes":[{...},{...}]
Ocelot參數說明如下,詳情查看官網(http://ocelot.readthedocs.io)
ReRoutes 路由配置
UpstreamPathTemplate 請求路徑模板
UpstreamHttpMethod 請求方法數組
DownstreamPathTemplate 下游請求地址模板
DownstreamScheme 請求協議,目前應該是支持http和https
DownstreamHostAndPorts 下游地址和埠
LoadBalancerOptions 負載均衡 RoundRobin(輪詢)/LeastConnection(最少連接數)/CookieStickySessions(相同的Sessions或Cookie發往同一個地址)/NoLoadBalancer(不使用負載)
DownstreamHostAndPorts配了兩個localhost 5011和localhost 5012用於負載均衡,負載均衡已經可以了,但沒有健康檢查,當其中一個掛了,負載可能還是會訪問這樣就會報錯,所以我們要加入Consul,我們稍後再講。
請求聚合,認證,限流,熔錯告警等查看官方配置說明
GlobalConfiguration 全局配置
BaseUrl 告訴別人網關對外暴露的功能變數名稱
1.2、修改 Program.cs 代碼,讀取Ocelot.json配置,修改網關地址為 http://localhost:5000
代碼如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Snai.ApiGateway
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) => {
builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
.AddJsonFile("Ocelot.json");
})
.UseUrls("http://localhost:5000")
.UseStartup<Startup>()
.Build();
}
}
1.3、修改Startup.cs代碼,註入Ocelot到容器,並使用Ocelot
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace Snai.ApiGateway
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseOcelot().Wait();
}
}
}
最終項目結構如下:
2、搭建服務Snai.ApiServiceA,Snai.ApiServiceB
新建 Snai.ApiServiceA 基於Asp.net Core 2.0 Api網站
2.1、修改Controllers/ValuesController.cs代碼
修改路由為Ocelot 配置的下游地址 apiservice/[controller],註入appsettings.json配置實體,修改Get方法為返回讀取配置內容,其他方法可以刪除