.net core Consul

创建API项目修改Program

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseUrls("http://127.0.0.1:5001");
    }
View Code

修改Startup

 public void Configure(IApplicationBuilder app, IHostingEnvironment env,IApplicationLifetime applicationLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
            //注册Consul

            //要注册的服务地址
            string ip = "http://127.0.0.1";
            //要注册的服务端口
            string port = "5001";
            string serviceName = "Values";
            string serviceId = "test123456789";
            using (var consulClient = new ConsulClient(ConsulConfig))
            {
                AgentServiceRegistration asr = new AgentServiceRegistration
                {
                    Address = ip,
                    Port = Convert.ToInt32(port),
                    ID = serviceId,
                    Name = serviceName,
                    //设置服务健康监测的服务,并设置轮询机制
                    //制定定期检测服务状况
                    Check = new AgentServiceCheck
                    {
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                        HTTP = "http://127.0.0.1:5001/api/Health",
                        Interval = TimeSpan.FromSeconds(10),
                        Timeout = TimeSpan.FromSeconds(5)
                    }
                };
                consulClient.Agent.ServiceRegister(asr).Wait();
            }
            applicationLifetime.ApplicationStopped.Register(() => {
                using (var consulClient = new ConsulClient(ConsulConfig))
                {
                    Console.WriteLine("应用退出,开始从Consul注销");
                    consulClient.Agent.ServiceDeregister(serviceId).Wait();
                }
            });
        }
        //Consul-配置委托
        private void ConsulConfig(ConsulClientConfiguration config)
        {
            //数据中心地址
            config.Address = new Uri("http://localhost:8500"); 
            config.Datacenter = "dc1";
        }
View Code

添加HealthController

[Produces("application/json")]
    [Route("api/Health")]
    public class HealthController : Controller
    {
       [HttpGet]
       public IActionResult Get()
        {
            Console.WriteLine("健康检查" + DateTime.Now);
            return Content("ok");
        }
         
    }
View Code

 

posted on 2019-08-08 16:13  为什么人的眼睛有黑白两色  阅读(215)  评论(0编辑  收藏  举报