一、为什么有consul?
在微服务,每1个服务都是集群式的,订单服务在10台服务器上都有,那么用户的请求到达,获取哪台服务器的订单服务呢?如果10台中的有的订单服务挂了怎么办?10台服务器扛不住了,水平扩展又新增加了1台服务器提供订单服务,怎么让用户请求知道有新的服务器提供服务了?这时候就需要Consul了,它能通过心跳检测哪些服务还活着,而且有新的服务启动,它也能主动发现
二、consul环境准备
1、consul环境
consul官网:https://www.consul.io/downloads.html,下载windows 64bit
2、启动consul管理后台
然后cmd启动,注意切盘符,路径要对,盘符切到放consul.exe的目录,cd D:\consul\consul agent -dev
访问consul管理后台:http://localhost:8500
三、代码实现
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 }); } } }
2、log4net 集成到Core
2.1、Nuget引入log4net
2.2、Nuget引入Microsoft.Extensions.Logging.Log4Net.AspNetCore
2.3、添加log4net 配置文件 (设置配置文件属性为始终复制,默认配置文件放在根目录下)
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、网站启动后需要consul注册
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.2、在Startup的Configure方法里使用consul
3.3、ConsulRegister心跳检测,添加health-check,健康检查
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、去http://localhost:8500查看多个服务被发现和心跳检测
原文地址:https://www.cnblogs.com/menglin2010/p/12114473.html