Consul可以用来进行服务发现,我们来测试下Consul的使用
一.Consul基本使用
先需要下载Consul的程序https://www.consul.io/downloads.html
我们这里下载Windows 64版本。
下载后直接解压就行了,里面会有一个consul.exe文件。通过命令可以启动consul.exe agent -dev
此时我们就可以在浏览器中通过http://localhost:8500/进行访问consul了
这就说明我们的consul启动成功了。
二.Consul和.net程序的结合使用
通过Consul来对.net程序进行服务发现可以有两种方法
通过代码的方式和通过配置文件的方式,下面我们就来讲下这两种方式怎么实现的吧
我们新建一个webapi项目ConsulDemo
A.代码的方式
通过nuget安装consul
创建一个webapi控制器HealthController只需简单的实现一个api返回ok就行了,这个是用来做健康监测的,监测这个webapi程序是否正常运行,能访问到就说明正常运行。
[Route("api/[controller]/[action]")][ApiController]public class HealthController : ControllerBase{public IActionResult Index() {return new OkResult();}}
然后创建一个ConsulHelper类
public static class ConsulHelper {public static void Init(this IConfiguration _configuration) {ConsulClient clinet = new ConsulClient(c => {c.Address = new Uri("http://localhost:8500/");c.Datacenter = "dcl";});string ip = "127.0.0.1";int port = 5000;clinet.Agent.ServiceRegister(new AgentServiceRegistration() {ID = "service" + Guid.NewGuid(),Name = "test",Address = ip,Port = port,Check = new AgentServiceCheck() {//此处就是健康监测需要配置的,配置刚才创建的Health监测的api控制器Interval = TimeSpan.FromSeconds(12),//间隔12秒一次HTTP = $"http://{ip}:{port}/API/Health/Index",Timeout = TimeSpan.FromSeconds(52),//检测等待时间DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60)//失败多久后移除,最小值60秒}}).Wait();}}
在Startup.cs的Configure中加上 ConsulHelper.Init(Configuration);这句话就行了
// 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();}ConsulHelper.Init(Configuration);app.UseMvc();}
此时我们将程序运行起来,可以看到有个test的服务了,这就说明Consul发现了我们刚启动的服务了,因为我们刚才配置中写了Name="test"
B.配置文件的方式
通过上面代码的方式,其实配置文件的方式应该更为简单方便,毕竟不用写代码了,只需修改下配置文件就行了。
在Consul目录下创建配置文件consul.json
{"service": {"id": "consul-service-test","name": "test","tags": [ "test" ],"address": "127.0.0.1","port": 5000,"checks": [{"http": "http://127.0.0.1:5000/api/Health/Index","interval": "10s"}]}
}
不过启动的命令得修改了,后面需加上配置文件的目录地址
consul agent -dev -config-dir=D:\Soft\consul_1.8.5_windows_amd64
这样webapi项目里其实上面都不用修改,只需要有健康监测的api就行了。Consul启动后就会自动取发现此webapi的服务了。