.NET 5.0實現Consul服務註冊
阿新 • • 發佈:2021-10-28
一.安裝Consul
進入/usr/local/src目錄
cd /usr/local/src
下載consul安裝壓縮包
wget http://releases.hashicorp.com/consul/1.10.1/consul_1.10.1_linux_amd64.zip
解壓壓縮包到當前目錄
unzip consul_1.10.1_linux_amd64.zip
解壓後有一個名字為consul的可執行檔案
檢視版本號
./consul --version
版本號為v1.10.1
建立consul.server目錄,並把consul檔案移動到coonsul.server目錄
mkdir consul.server mv consul consul.server
在consul.server目錄裡建立consul.d目錄
cd consul.server
mkdir consul.d
在consul.d目錄中建立webservice.json檔案
cd consul.d/
touch webservice.json
./consul agent -server -ui -bootstrap-expect=1 -data-dir=/usr/local/src/consul.server -node=agent-one -advertise=172.19.43.49 -bind=0.0.0.0 -client=0.0.0.0
訪問8500埠即可看到consul註冊節點
二.註冊服務
建立一個.NET Core工程,新增Consul包。
新增一個名為HealthController的控制器,並實現一個get請求的介面用於服務健康檢查,介面返回StatusCode為200。
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Pudefu.Web.Controllers { [Route("api/[controller]")] [ApiController] public class HealthController : ControllerBase { [HttpGet] public JsonResult Get() { return new JsonResult("OK"); } } }
在配置檔案appsettings.json新增配置
"ConsulConfig": { "ServiceId": "d72e7de8b01a43acac640b1a00b26c81", "ServiceName": "pudefu.web", "ServiceIP": "xxx.xx.xxx.xx",//當前應用部署的伺服器IP地址 "ServicePort": 8000,//當前應用部署的伺服器埠 "ConsulIP": "xxx.xx.xxx.xx",//Consul部署的伺服器IP地址 "ConsulPort": 8500//Consul埠 }
新增服務配置模型
public class ServiceConfig { /// <summary> /// 服務唯一ID /// </summary> public string ServiceId { get; set; } /// <summary> /// 服務部署的IP /// </summary> public string ServiceIP { get; set; } /// <summary> /// 服務部署的埠 /// </summary> public int ServicePort { get; set; } /// <summary> /// 服務名稱 /// </summary> public string ServiceName { get; set; } /// <summary> /// consul部署的IP /// </summary> public string ConsulIP { get; set; } /// <summary> /// consul埠 /// </summary> public int ConsulPort { get; set; } }
新增Consul註冊類
public static class AppBuilderExtensions { public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IHostApplicationLifetime lifetime, ServiceConfig serviceConfig) { var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceConfig.ConsulIP}:{serviceConfig.ConsulPort}")); var httpCheck = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//伺服器啟動5秒後註冊 Interval = TimeSpan.FromMinutes(1),//每分鐘檢測一次(健康檢查間隔時間) HTTP = $"http://{serviceConfig.ServiceIP}:{serviceConfig.ServicePort}/api/health",//本服務健康檢查地址 Timeout = TimeSpan.FromSeconds(20), }; var registerAgent = new AgentServiceRegistration() { Check = httpCheck, Checks = new[] { httpCheck }, ID = serviceConfig.ServiceId,//一定要指定服務ID,否則每次都會建立一個新的服務節點 Name = serviceConfig.ServiceName, Address = serviceConfig.ServiceIP, Port = serviceConfig.ServicePort, Tags = new[] { $"urlprefix-/{serviceConfig.ServiceName}" }//新增 urlprefix-/servicename 格式的tag標籤,以便Fabio識別 }; consulClient.Agent.ServiceRegister(registerAgent).Wait();//服務啟動時註冊,使用Consul API進行註冊(HttpClient發起) lifetime.ApplicationStopped.Register(() => { consulClient.Agent.ServiceDeregister(registerAgent.ID).Wait();//伺服器停止時取消註冊 }); return app; } }
在Startup中添加註冊程式碼
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //app.UseHttpsRedirection(); //DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); //defaultFilesOptions.DefaultFileNames.Clear(); //defaultFilesOptions.DefaultFileNames.Add("Index.html"); //app.UseDefaultFiles(defaultFilesOptions); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); var serviceConfig = Configuration.GetSection("ConsulConfig").Get<ServiceConfig>(); app.RegisterConsul(lifetime, serviceConfig); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); endpoints.MapRazorPages(); }); }
釋出啟動後,可見以下注冊成功的服務
點選pudefu.web(服務名稱)這個服務可以檢視服務詳細資訊
服務健康檢查成功:
服務健康檢查失敗: