.NetCore3.1接入Consul的服务端和客户端代码整理

服务端

  1. Nuget引用Consul
  2. 代码:
  1. 添加配置

Appsetting.json添加配置项

"ConsulConfig": {

          "ConsulAddress": "http://consul.zyiz.net", //consul注册中心地址

          "Token": "",//consul鉴权token,暂未有

          "ServiceName": "servicename", //服务名称,各个应用自定,不要重复

          "ServicePort": 80 //当前服务开启的http端口

  }

 

 配置类代码:  

public class ConsulRegConfig

    {

        public string ConsulAddress { get; set; }

        public string Token { get; set; }



        public string ServiceName

        {

            get;

            set;

        }



        public int ServicePort

        {

            get;

            set;

        }

    }

2)StartUp添加代码读取配置

     

  //读取配置

private ConsulRegConfig consulConfig;

//服务节点ID

        private static string globalguid = Guid.NewGuid().ToString("N");



        public Startup(IConfiguration configuration)

        {

            consulConfig = configuration.GetSection("ConsulConfig").Get();

        }

3) StartUp添加自动注册服务代码

public void Configure(IApplicationBuilder app, IHostingEnvironment env,IHostApplicationLifetime applicationLifetime)

        {

           

                #region 自动注册服务

                applicationLifetime.ApplicationStarted.Register(() =>

                {

                    using (var consulClient = new ConsulClient(c =>

                    {

                        c.Address = new Uri(consulConfig.ConsulAddress);

                        c.Token = consulConfig.Token;



                    }))

                    {

                        int times = 0;

                        while (times++ < 10)

                        {

                            try

                            {

                                var ipaddress = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()

                                                .Select(p => p.GetIPProperties())

                                                .SelectMany(p => p.UnicastAddresses)

                                                .Where(p => p.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !System.Net.IPAddress.IsLoopback(p.Address))

                                                .Select(p => p.Address.ToString()).ToArray().First();

                                AgentServiceRegistration asr = new AgentServiceRegistration

                                {

                                    Address = ipaddress,

                                    Port = this.consulConfig.ServicePort,

                                    ID = globalguid,

                                    Name = this.consulConfig.ServiceName,

                                    Check = new AgentServiceCheck

                                    {

                                        DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(120),

                                        HTTP = $"http://{ipaddress}:{this.consulConfig.ServicePort}/Health",

                                        Interval = TimeSpan.FromSeconds(30),

                                        Timeout = TimeSpan.FromSeconds(10),

                                    },

                                };

                                var task = consulClient.Agent.ServiceRegister(asr);

                                task.Wait();

                                Console.WriteLine($"服务注册结果:{task.Result.StatusCode.ToString()}");



                                if (task.Result.StatusCode == System.Net.HttpStatusCode.OK)

                                {

                                    break;

                                }

                            }

                            catch(Exception ex)

                            {

                                Console.WriteLine($"服务注册失败:{ex.ToString()}");

                            }



                            Thread.Sleep(times * 500);

                        }

                    }

                });



                //程序退出注销服务

                applicationLifetime.ApplicationStopping.Register(() =>

                {

                    using (var consulClient = new ConsulClient(c =>

                    {

                        c.Address = new Uri(consulConfig.ConsulAddress);

                        c.Token = consulConfig.Token;



                    }))

                    {

                        Console.WriteLine("应用退出,开始从consul注销");

                        consulClient.Agent.ServiceDeregister(globalguid).Wait();

                    }

                });

                #endregion



        }

 

客户端

  1. Nuget引用Consul
  2. 获取服务地址(示例)
/// 

        /// 根据consul服务名查询服务地址

        /// 

        /// consul服务名

        /// 随机返回一条可用的地址

        public string GetServiceBaseUrlByServiceName(string serviceName)

        {

            using (ConsulClient client = new Consul.ConsulClient(c =>

            {

                c.Address = new Uri("http://consul.zyiz.net/");

                c.Token = "";

            }))

            {

                //这里建议加几秒钟缓存抗大量并发请求

                var services = client.Health.Service(serviceName, string.Empty, true);



                ServiceEntry[] servicelist = services.Result.Response;



                string serviceHost;

                if (servicelist.Length == 0)

                {

                    serviceHost = string.Empty;

                }

                else if (servicelist.Length == 1)

                {

                    serviceHost = $"http://{servicelist[0].Service.Address}:{servicelist[0].Service.Port}";

                }

                else

                {

                    var service = servicelist[new Random().Next(0, servicelist.Length)].Service;

                    serviceHost = $"http://{service.Address}:{service.Port}";

                }



                return serviceHost;

            }

        }

 

你可能感兴趣的:(NetCore)