.Net Core微服务之Consul部署

1、创建.Net Core项目,创建ConsulBuilderExtensions 扩展类

引用Consul类库:Install-Package Consul -Version 0.7.2.6

 public static class ConsulBuilderExtensions
    {

        // 服务注册

        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, HealthService healthService, ConsulService consulService)

        {

            var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{consulService.IP}:{consulService.Port}"));//请求注册的 Consul 地址

            var httpCheck = new AgentServiceCheck()

            {

                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册

                Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔

                HTTP = $"https://{healthService.IP}:{healthService.Port}/api/health",//健康检查地址

                Timeout = TimeSpan.FromSeconds(5)

            };

            // Register service with consul

            var registration = new AgentServiceRegistration()

            {

                Checks = new[] { httpCheck },

                ID = healthService.Name + "_" + healthService.Port,

                Name = healthService.Name,

                Address = healthService.IP,

                Port = healthService.Port,

                Tags = new[] { $"urlprefix-/{healthService.Name}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别

            };

            consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)

            lifetime.ApplicationStopping.Register(() =>

            {

                consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册

            });

            return app;

        }

2、创建检查服务类及Consul服务类

/// <summary>
    /// 检查服务
    /// </summary>
    public class HealthService
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// IP
        /// </summary>
        public string IP { get; set; }
        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }

    }
 /// <summary>
    /// Consul服务
    /// </summary>
    public class ConsulService
    {
        /// <summary>
        /// IP
        /// </summary>
        public string IP { get; set; }
        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }
    }

3、在Startup.cs下修改Configure函数如下

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

            app.UseHttpsRedirection();
            app.UseMvc();

            #region register this service

            ConsulService consulService = new ConsulService()

            {

                IP = Configuration["Consul:IP"],

                Port = Convert.ToInt32(Configuration["Consul:Port"])

            };

            HealthService healthService = new HealthService()

            {

                IP = Configuration["Service:IP"],

                Port = Convert.ToInt32(Configuration["Service:Port"]),

                Name = Configuration["Service:Name"],

            };

            app.RegisterConsul(lifetime, healthService, consulService);

            #endregion
        }

4、修改appsetting.json

 "Service": {

    "Name": "NetCoreConsul",

    "IP": "localhost",

    "Port": "5001"

  },

  "Consul": {

    "IP": "localhost",

    "Port": "8500"

  }

5、运行项目并保证项目能够正常运行

.Net Core微服务之Consul部署

6、打开cmd执行consul命令

 consul agent -server -ui -bootstrap-expect=3 -data-dir=/tmp/consul  -node=consul-80 -client=0.0.0.0  -bind=127.0.0.1 -datacenter=dc1

.Net Core微服务之Consul部署执行.net core项目,浏览器输入:172.0.0.1:8500

.Net Core微服务之Consul部署

可以看到我们项目项目已添加到集群中,接下来浏览器查看服务发现 

http://127.0.0.1:8500/v1/catalog/service/NetCoreConsul

.Net Core微服务之Consul部署