1.下载Consul
2.在Consul程序所在文件夹使用CMD命令:consul.exe agent -dev
3.打开浏览器输入: http://loclhost:8500
4.注册服务与发现服务(应在项目执行时进行注册)
1)打开接口项目
2)引用Consul包
3)新建HealthController 写健康检查接口(通过调用接口,根据返回状态判断是否正常)
[Route("api/[controller]/[action]")] [ApiController] public class HealthController : ControllerBase { public IActionResult Index() { return new JsonResult("ok"); } }
4)新建一个ConsulHelper帮助类,定义一个注册方法
public static void ConsulRegist(this IConfiguration configuration) { ConsulClient client = new ConsulClient(c => { c.Address = new Uri("http://localhost:8500"); c.Datacenter = "dc1"; }); // 该项目文件夹下cmd命令:dotnet xx.dll --urls="http://*:9090" --ip:"127.0.0.1" --port:9090 var address = configuration["ip"]; // 使用命令执行项目传递的ip地址; var port = int.Parse(configuration["port"]); // 使用命令执行项目传递的端口 client.Agent.ServiceRegister(new AgentServiceRegistration() { ID = "service" + Guid.NewGuid(), // 唯一的 Name = "BesosService", // 组名称-Group Address = address, Port = port, Tags = new string[] { $"http://{address}:{port}/api/Health/Index" }, // 标签,
// 心跳健康检查 Check = new AgentServiceCheck() { Interval = TimeSpan.FromSeconds(12), // 间隔12s一次 HTTP = $"http://{address}:{port}/api/Health/Index", // 调健康检查接口 Timeout = TimeSpan.FromSeconds(5), // 检查等待时间 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60) // 失败后多久移除 最小值60s } }) ; }
5)可放在Starup.cs文件的Configure方法中或者Program.cs文件的主程序入库处
// 执行且执行一次,注册Consul ConsulHelper.ConsulRegist();
6)服务的发现(如何获得已注册的服务的信息)
public void Found() { ConsulClient client = new ConsulClient(c => { c.Address = new Uri("http://localhost:8500"); c.Datacenter = "dc1"; }) var response = client.Agent.Services().Result.Response; var serviceDictionary = response.Where(c => c.Value.Service.Equals("BesosService", StringComparison.OrdinalIgnoreCase)) .ToArray(); }