前言
.Net Core 已經發布3.0了在最近的一兩年中.NET Core的關注度持續上升, 微服務及雲原生應用開發上采用.NET Core也越來越多,Ocelot 作為.NET Core平台下一款開源的API 網關開發庫越來越得到社區的認可,應用到生產中的案例也很多,本文分享以下兩部分內容
1、基於Ocelot搭建Api網關;2、Ocelot+Consul 實現下游服務的服務注冊、服務發現、健康檢查、負載均衡 參考 《.NET Core 在騰訊財付通的企業級應用開發實踐》。
先給大解釋下Ocelot 和 Consul到底是干啥的
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.1
Ocelot:7.1.0
Consul:1.1.0 github 分享地址 (https://github.com/zhangbojr/Consul.git)
項目解決方案目錄
Bo.ApiGateway Asp.net Core 2.0 Api網關
Bo.ApiServiceA Asp.net Core 2.0 Api下游服務A
Bo.ApiServiceB Asp.net Core 2.0 Api下游服務B
Consul:
conf 配置目錄
data 緩存數據目錄,可清空里面內容
dist Consul UI目錄
consul.exe 注冊軟件
startup.bat 執行腳本
項目實現
1、搭建Api網關
新建Bo.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 Bo.ApiGateway { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, builder) => { builder.SetBasePath(context.HostingEnvironment.ContentRootPath) .AddJsonFile("Ocelot.json"); }).UseUrls("http://localhost:5000") .UseStartup<Startup>(); } }
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 Bo.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(); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } } }
2、搭建服務Bo.ServiceA,Bo.ServiceB 基於Asp.net Core 2.0 Api網站
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace Bo.ServiceA.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { public IConfiguration Configuration { get; } public ValuesController(IConfiguration configuration) { Configuration = configuration; } [HttpGet] public string Get() { return HttpContext.Request.Host.Port + " " + Configuration["AppName"] + " " + DateTime.Now.ToString(); } [HttpGet("/health")] public IActionResult Heathle() { return Ok(); } // GET api/values // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
2.2、修改appsettings.json配置,加入 "AppName": "ServiceA"
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "AppName": "ServiceA" }
2.3、修改Program.cs代碼,修改該服務地址為 http://localhost:5011
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 Bo.ServiceA { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseUrls("http://192.168.2.6:5011") .UseStartup<Startup>(); } }
2.4、新建Bo.ServiceB 基於Asp.net Core 2.0 Api網站,幾乎與ServiceA一樣,除了 "AppName": "ServiceB",.UseUrls("http://localhost:5012")
3、啟動 運行Bo.ServiceA,Bo.ServiceB,Bo.ApiGateway項目,在瀏覽器打開 http://localhost:5000/apiservice/values 地址
Ocelot已內置負載均衡,但沒有健康檢查,不能踢除壞掉的服務,所以加入Consul,Consul提供服務注冊發現、健康檢查,配合Ocelot負載就能發現壞掉的服務,只負載到正常的服務上,下面介紹加入Consul。
二、在Ocelot網關加入Consul,實現服務注冊發現、健康檢查
1、啟動Consul,開啟服務注冊、服務發現
首先下載Consul:https://www.consul.io/downloads.html,本項目是windows下進行測試,得到consul.exe
再下載Consul配置文件和Consul UI(配置文件適合本例Demo的,可根據具體項目修改調整):https://github.com/Liu-Alan/Ocelot-Consul/tree/master/Consul
conf:配置文件目錄
data:緩存數據目錄,可清空里面內容
dist:Consul UI,用於瀏覽器查看注冊的服務情況;如果用Consul默認自帶UI,該目錄可以刪除,Consul 啟動腳本 -ui-dir ./dist 改為 -ui
Consul支持配置文件和Api兩種方式服務注冊、服務發現,下面主要講解配置文件方式
Consul 配置文件service.json配置如下:
{ "encrypt": "7TnJPB4lKtjEcCWWjN6jSA==", "services": [ { "id": "ApiServiceA", "name": "MyService", "tags": ["ApiServiceA"], "address": "192.168.2.6", "port": 5011, "checks": [ { "id": "CK A 5011", "name": "CK A 5011", "http": "http://192.168.2.6:5011/health", "interval": "5s", "tls_skip_verify": false, "method": "GET", "timeout": "1s" } ] } ] }
打開ValuesController.cs 加入 health
重新生成運行項目Bo.ServiceA,Bo.ServiceB
清除Consul/data 內容,新建startup.bat文件,輸入下面代碼,雙擊啟動Consul,本項目測試時一台機器,所以把 本機IP 改成 192.168.2.6
consul agent -server -datacenter=dc1 -bootstrap -data-dir ./data -config-file ./conf -ui-dir ./dist -node=n1 -bind 本機IP -client=0.0.0.0
再在Consul目錄下啟動另一個cmd命令行窗口,輸入命令:consul operator raft list-peers 查看狀態查看狀態,結果如下
由於ServiceA、ServiceB是在一台機器上兩個服務做負載 所以在一個Consul里配置了兩個name一樣的服務。
如果用兩個機器做ServiceA負載,本機IP是192.168.2.6,另一台IP是192.168.2.180上,以本機上主Consul
把ServiceB和Consul拷到另一個192.168.2.180 機器,修改Consul配置文件
修改啟動Consul腳本的IP為192.168.2.180,-node=n2,去掉 -bootstrap,啟動Consul,在Consul UI下查看服務是否正常
在192.168.2.6下,把192.168.2.180加到集群中,命令如下
consul join 192.168.2.180
注意,consul集群中,consul配置文件中的encrypt,一定要相同,否則無法放加入同一個集群
用consul operator raft list-peers查看狀態,會發現n1,n2在一個集群中了
2、配置Ocelot,加入Consul,啟用服務健康檢查,負載均衡
打開 Snai.ApiGateway 網關下的Ocelot.json文件,加入下面配置
ServiceName 是Cousul配置中服務的name名字
UseServiceDiscovery 是否啟用Consul服務發現
ServiceDiscoveryProvider 是Consul服務發現的地址和端口
重新生成啟動Ocelot網關,到此Ocelot+Consul配置完成
三、運行測試Ocelot+Consul服務發現、負載均衡
打開 http://localhost:5000/api/values 地址,刷新頁面負載得到ServiceA,ServiceB返回內容
當把ServiceB服務關掉,再多次刷新頁面,只能得到ServiceA的內容
源碼地址:(https://github.com/zhangbojr/.Net-core-Ocelot-Consul.git)