环境:
window10 x64vs2019 16.7.4.asp.netcore 3.1consul_1.8.4_windows_amd64.zip本实验代码下载:https://download.csdn.net/download/u010476739/12998910
方式一:官网下载: https://www.consul.io/downloads 方式二、网盘下载 链接:https://pan.baidu.com/s/1p-aMgpAMZKgxlbvu0FMoUA 提取码:vpge 复制这段内容后打开百度网盘手机App,操作更方便哦–来自百度网盘超级会员V3的分享
Consule是go语言开发的,主要用于服务的注册和发现的。。。
解压Consul后就一个exe文件,如下: 命令行运行:consul.exe agent -dev,运行后如下: 浏览器访问:http://localhost:8500,如下:
先建一个空白解决方案:ConsulTrial,然后新建个WebApi项目:OrderApi和控制台项目:ConsulRequest,如下: 在OrderApi项目中添加Consul包引用:
<ItemGroup> <PackageReference Include="Consul" Version="1.6.1.1" /> </ItemGroup>在OrderApi项目中新建HealthController控制器,来接受Consul的健康检查:
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OrderApi.Controllers { [ApiController] [Route("api/[controller]")] public class HealthController : ControllerBase { [HttpGet] public string Get() => "ok"; } }在Startup.cs中新建方法用来注册Consul服务:
public static void RegisterConsul() { var consulClient = new ConsulClient(p => { p.Address = new Uri($"http://127.0.0.1:8500"); });//请求注册的 Consul 地址 //这里的这个ip 就是本机的ip,这个端口8500 这个是默认注册服务端口 var httpCheck = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册 Interval = TimeSpan.FromSeconds(10),//间隔固定的时间访问一次,https://localhost:44308/api/Health HTTP = $"https://localhost:5001/api/Health",//健康检查地址 44308是visualstudio启动的端口 Timeout = TimeSpan.FromSeconds(5) }; var registration = new AgentServiceRegistration() { Checks = new[] { httpCheck }, ID = Guid.NewGuid().ToString(), Name = "test1", Address = "https://localhost/", Port = 5001, }; consulClient.Agent.ServiceRegister(registration).Wait();//注册服务 //consulClient.Agent.ServiceDeregister(registration.ID).Wait();//registration.ID是guid //当服务停止时需要取消服务注册,不然,下次启动服务时,会再注册一个服务。 //但是,如果该服务长期不启动,那consul会自动删除这个服务,大约2,3分钟就会删了 }然后将方法调用加到Configure方法中:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); RegisterConsul(); }运行这个WebApi项目: 此时,再看下Consul的web页面:
首先在控制项目ConsulRequest中引入Consul包:
<ItemGroup> <PackageReference Include="Consul" Version="1.6.1.1" /> </ItemGroup>然后,修改Program代码:
using Consul; using System; using System.Linq; namespace ConsulRequest { class Program { static void Main(string[] args) { var consulClient = new ConsulClient(x => x.Address = new Uri($"http://127.0.0.1:8500"));//请求注册的 Consul 地址 var ret = consulClient.Agent.Services(); var allServer = ret.GetAwaiter().GetResult(); //这个是个dictionary的返回值,他的key是string类型,就是8500/ui上services的instance的id var allServerDic = allServer.Response; var test1 = allServerDic.First(); string name = test1.Value.Service;//服务名,就是注册的那个test1 string serverAddress = test1.Value.Address; int serverPort = test1.Value.Port; Console.WriteLine($"serverAddress:{serverAddress}==serverPort{serverPort}"); //我们可以在客户端启动的时候,调用一下consul来查找服务 //比如,我们可以在服务集合里查找 服务名叫test1的服务 然后在调用它 //这样,当服务器改变了test1的ip和端口,我们依然可以在集群里找他test1新的ip和端口了 Console.ReadLine(); } } }运行效果如下:
当启动web服务后向consul注册服务,那么web服务关闭时可以直接向consul发起注销请求,将上面代码改造如下:
public static void RegisterConsul(IHostApplicationLifetime hostApplicationLifetime) { var consulClient = new ConsulClient(p => { p.Address = new Uri($"http://127.0.0.1:8500"); });//请求注册的 Consul 地址 //这里的这个ip 就是本机的ip,这个端口8500 这个是默认注册服务端口 var httpCheck = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册 Interval = TimeSpan.FromSeconds(10),//间隔固定的时间访问一次,https://localhost:44308/api/Health HTTP = $"https://localhost:5001/api/Health",//健康检查地址 44308是visualstudio启动的端口 Timeout = TimeSpan.FromSeconds(5) }; var registration = new AgentServiceRegistration() { Checks = new[] { httpCheck }, ID = Guid.NewGuid().ToString(), Name = "test1", Address = "https://localhost/", Port = 5001, }; consulClient.Agent.ServiceRegister(registration).Wait();//注册服务 hostApplicationLifetime.ApplicationStopped.Register(() =>consulClient.Agent.ServiceDeregister(registration.ID).Wait()); }在startup调用时传入生命周期对象:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime hostApplicationLifetime) { //... RegisterConsul(hostApplicationLifetime); }参考:c#:配置Consul为window服务