consul命令行查看服务_1、微服务--为什么有consul,consul注册,心跳检测,服务发现...

一、为什么有consul?

在微服务,每1个服务都是集群式的,订单服务在10台服务器上都有,那么用户的请求到达,获取哪台服务器的订单服务呢?如果10台中的有的订单服务挂了怎么办?10台服务器扛不住了,水平扩展又新增加了1台服务器提供订单服务,怎么让用户请求知道有新的服务器提供服务了?这时候就需要Consul了,它能通过心跳检测哪些服务还活着,而且有新的服务启动,它也能主动发现

f12e4f8d263c7f515eed802c71371c2a.png

二、consul环境准备

1、consul环境

consul官网:https://www.consul.io/downloads.html,下载windows 64bit

2、启动consul管理后台

然后cmd启动,注意切盘符,路径要对,盘符切到放consul.exe的目录,cd D:consulconsul agent -dev

访问consul管理后台:http://localhost:8500

6967c86e16bd76f27e85d983e0c846cd.png
3a7b47d5855b0ec311ac7c19558236df.png

三、代码实现

1、添加Webapi服务

namespace ConsulServiceFind.Controllers{    [Route("api/[controller]")]    [ApiController]    public class ValuesController : ControllerBase    {        private IConfiguration _IConfiguration = null;        private ILogger _logger = null;        public ValuesController(IConfiguration iConfiguration, ILogger logger)        {            _IConfiguration = iConfiguration;            _logger = logger;        }        // GET api/values        [HttpGet]        public ActionResult> 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();    }}

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 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

85f4ebc63d66b95c3797a9745b44faee.png

3.3、ConsulRegister心跳检测,添加health-check,健康检查

namespace ConsulServiceFind{    [Route("api/[controller]")]    [ApiController]    public class HealthController : ControllerBase    {        private IConfiguration _IConfiguration = null;        private ILogger _logger = null;        public HealthController(IConfiguration configuration, ILogger 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:甥敳獲dellDesktopConsulServiceFindConsulServiceFindbinDebugetcoreapp2.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

befedb74666f6430b6f83c5ebb2f75e9.png
3cfbd3a1a642e8c411fdb235e1d72f62.png

4.3、去http://localhost:8500查看多个服务被发现和心跳检测

0af4b3867ce6b8c590ab00cdd716f5f9.png
3d4c7b08dd567fd3a5c321cb884aec4e.png

举例和生活相结合,做一条快乐的小

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值