Net6+Consul的简单使用

发布时间 2023-09-16 16:14:19作者: 孤海飞雁
先下载Consul

打开cmd

consul.exe agent -dev运行
可以在环境变量 PATH下添加当前
Consul.exe 路径 全局使用
下面试启动ok界面,然后通过 localhost:8500 看到界面了




 

然后创建两个 api 程序,添加如下代码,

 [HttpGet("start")]
        public void Start()
        {
            string local = HttpContext.Request.Host.Host;
            int port = (int)HttpContext.Request.Host.Port!;
            string? url = HttpContext.Request.Host.Value;
            string? scheme = HttpContext.Request.Scheme + "://";
            //   int port = HttpContext.Request;

            //cmd 输入 consul 启动程序
            var consulClient = new ConsulClient(p => { p.Address = new Uri($"http://127.0.0.1:8500"); });//请求注册的 Consul 地址
                                                                                                         //这里的这个ip 就是本机的ip,这个端口8500 这个是默认注册服务端口 
            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),//间隔固定的时间访问一次,https://localhost:44308/api/Health
                HTTP = $"{scheme + url}/WeatherForecast/HealthCheck",//健康检查地址  ,就是下main的方法
                Timeout = TimeSpan.FromSeconds(5)
            };

            var registration = new AgentServiceRegistration()
            {
                Checks = new[] { httpCheck },
                ID = Guid.NewGuid().ToString() + "webapi1",
                Name = "test1",
                Address = $"{scheme + local}",
                Port = port,

            };

            consulClient.Agent.ServiceRegister(registration).Wait();//注册服务 

            //consulClient.Agent.ServiceDeregister(registration.ID).Wait();//registration.ID是guid
            //当服务停止时需要取消服务注册,不然,下次启动服务时,会再注册一个服务。
            //但是,如果该服务长期不启动,那consul会自动删除这个服务,大约2,3分钟就会删了 


        }
        [HttpGet("HealthCheck")]
        public bool HealthCheck() {//这里用于检测程序有没有挂的,这里要和上面对上,不然注册后也会是红叉,这里也坑了我一些时间
            Console.WriteLine("ok");
            return true;
        }

  成功

 

同一项目多次注册