服務注冊與發現
因為Consul對.net core的支撐和對Ocelot的高度兼容性,所以,.net core使用的服務注冊與發現的組件大多數使用的Consul。
首先。我有一個測試服務A。這個服務會進行服務注冊。用於對外提供服務。
服務A :
首先,Nuget安裝Consul
添加一個擴展類ConsulExtensions
public static class ConsulExtensions { public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IConfiguration configuration)//, IHostApplicationLifetime lifetime) { var consulClient = new ConsulClient(c => { c.Address = new Uri(configuration["ConsulSetting:ConsulAddress"]); }); var registration = new AgentServiceRegistration() { ID = Guid.NewGuid().ToString(),//服務實例唯一標識 Name = configuration["ConsulSetting:ServiceName"],//服務名 Address = configuration["ConsulSetting:ServiceIP"], //服務IP Port = int.Parse(configuration["ConsulSetting:ServicePort"]),//服務端口 因為要運行多個實例,端口不能在appsettings.json里配置,在docker容器運行時傳入 Check = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服務啟動多久后注冊 Interval = TimeSpan.FromSeconds(10),//健康檢查時間間隔 HTTP = $"http://{configuration["ConsulSetting:ServiceIP"]}:{configuration["ConsulSetting:ServicePort"]}{configuration["ConsulSetting:ServiceHealthCheck"]}",//健康檢查地址 Timeout = TimeSpan.FromSeconds(5)//超時時間 } }; //服務注冊 consulClient.Agent.ServiceRegister(registration).Wait(); ////應用程序終止時,手動取消注冊 //lifetime.ApplicationStopping.Register(() => //{ // consulClient.Agent.ServiceDeregister(registration.ID).Wait(); //}); return app; } }
在Starup里面注冊Consul服務
app.RegisterConsul(context.GetConfiguration());
在appsettings.json里面添加配置
"ConsulSetting": { "ServiceName": "TestService", "ServiceIP": "localhost", "ServiceHealthCheck": "/healthcheck", "ServicePort": "5000", "ConsulAddress": "http://localhost:8500" }
啟動服務,在Consul里面就能看見這個服務已經注冊進去了
現在再開始進入測試服務B,這個服務用於服務發現,並調用測試服務A的接口。
首先,還是先安裝Consul組件。然后創建一個IConsulTestAppService,並用ConsulTestAppService實現它。
public class ConsulTestAppService : IConsulTestAppService { private readonly IConfiguration _configuration; public ConsulTestAppService(IConfiguration configuration) { _configuration = configuration; } public async Task<string> GetAsync() { var consulClient = new ConsulClient(c => { //consul地址 c.Address = new Uri(_configuration["ConsulSetting:ConsulAddress"]); }); var services = consulClient.Health.Service("TestService", null, true, null).Result.Response;//健康的服務 string[] serviceUrls = services.Select(p => $"http://{p.Service.Address + ":" + p.Service.Port}").ToArray();//訂單服務地址列表 if (!serviceUrls.Any()) { return await Task.FromResult("【TestService】服務列表為空"); } //每次隨機訪問一個服務實例 var Client = new RestClient(serviceUrls[new Random().Next(0, serviceUrls.Length)]); var request = new RestRequest("/api/test/GetOne", Method.GET); var response = await Client.ExecuteAsync(request); return response.Content; } }
我這里使用RestSharp來進行Http請求。
訪問服務,TestService已經正常響應數據。