【微服务治理】Consul服务注册与发现,健康检查
一.为什么有Consul?
在微服务架构中,每1个服务都是集群式的提供服务,订单服务在10台服务器上都有,那么用户的请求到达,获取哪台服务器的订单服务呢?如果10台中有的订单服务挂了怎么办?10台服务器扛不住了,水平扩展又新增加了1台服务器提供订单服务,怎么让用户请求知道有新的服务器提供订单服务了?这时候就需要Consul了,它能通过心跳检测哪些服务还活着,而且有新的服务启动,它也能够主动发现。
1.S-B-1服务,S-B-2服务,S-B-3服务注册到Consul
2.Consul健康检查S-B-1服务,S-B-2服务,S-B-3服务
3.S-A调用S-B-1服务,或S-B-2服务,或S-B-3服务
二.Consul环境准备
2.1.Consul环境下载
Consul官网:https://www.consul.io/downloads.html,下载windows 64bit
2.2.启动Consul管理后台
盘符切到放consul.exe的目录,然后cmd启动,cd D:\consul\consul agent -dev
2.3.访问Consul管理后台:http://localhost:8500
三.代码落地
3.1.添加WebApi服务
namespace ConsulServiceFind.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private IConfiguration _IConfiguration = null; private ILogger<ValuesController> _logger = null; public ValuesController(IConfiguration iConfiguration, ILogger<ValuesController> logger) { _IConfiguration = iConfiguration; _logger = logger; } // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { this._logger.LogWarning("ValuesController-Get 执行"); return new JsonResult(new { Id = 123, Name = "david_test", IP = this._IConfiguration["ip"], port = this._IConfiguration["port"], urls = this._IConfiguration["urls"], CurrentPath = base.HttpContext.Request.Path }); } } }
3.2.log4net 集成到Core
3.2.1.Nuget引入log4net
3.2.2.Nuget引入Microsoft.Extensions.Logging.Log4Net.AspNetCore
3.2.3.添加log4net 配置文件 (设置配置文件属性为始终复制,默认配置文件放在根目录下)
3.2.4.注入ILogger
namespace ConsulServiceFind { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureLogging((context, LoggingBuilder) =>//ILogger { LoggingBuilder.AddFilter("System", LogLevel.Warning); //忽略系统的其他日志 LoggingBuilder.AddFilter("Microsoft", LogLevel.Warning); LoggingBuilder.AddLog4Net(); }) .UseStartup<Startup>(); } }
3.3.网站启动后需要Consul注册
3.3.1.Nuget引用Consul后,封装ConsulRegister类
namespace ConsulServiceFind { public static class ConsulRegister { public static void RegistConsul(this IConfiguration configuration) { string ip = configuration["ip"] ?? "Localhost"; //部署到不同服务器的时候不能写成127.0.0.1或者0.0.0.0,因为这是让服务消费者调用的地址 int port = int.Parse(configuration["port"]); //实例化Consul客户端 ConsulClient consulClient = new ConsulClient(c => { c.Address = new Uri("http://127.0.0.1:8500"); c.Datacenter = "consul"; }); //向Consul注册服务 Task<WriteResult> result = consulClient.Agent.ServiceRegister(new AgentServiceRegistration() { ID = "david_webapi_test_" + Guid.NewGuid(),//服务编号,不能重复 Name = "david_webapi",//服务的名字--将来调用时用的就是这个 Address = ip, Port = port, Tags = new string[] { },//可以用来设置权重 Check=new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务停止多久后反注册 Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔 HTTP = $"http://{ip}:{port}/api/health",//健康检查地址 Timeout = TimeSpan.FromSeconds(5) } }); } } }
3.3.2.在Startup的Configure方法里使用Consul
3.3.3.ConsulRegister心跳检测,添加HealthCheck也就是另外一个WebApi,做健康检查
namespace ConsulServiceFind { [Route("api/[controller]")] [ApiController] public class HealthController : ControllerBase { private IConfiguration _IConfiguration = null; private ILogger<HealthController> _logger = null; public HealthController(IConfiguration configuration, ILogger<HealthController> logger) { this._IConfiguration = configuration; this._logger = logger; } [HttpGet] public IActionResult Check() { this._logger.LogWarning($"{this._IConfiguration["port"]}-Health Check!"); return Ok();//200 } } }
4.启动多个WebApi实例,运行两个WebApi服务起来
4.1.cd 切路径-C:\Users\dell\Desktop\ConsulServiceFind\ConsulServiceFind\bin\Debug\netcoreapp2.2
4.2.通过命令行启动2个不同端口的WebApi
dotnet ConsulServiceFind.dll --urls="http://*:10010" --ip="127.0.0.1" --port=10010
dotnet ConsulServiceFind.dll --urls="http://*:10020" --ip="127.0.0.1" --port=10020
http://localhost:10010/api/values
http://localhost:10020/api/values
4.3.去Consul管理后台http://localhost:8500查看多个服务被发现和心跳检测