.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<ConsulRegConfig>();

        }

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. 获取服务地址(示例)
/// <summary>

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

        /// </summary>

        /// <param name="serviceName">consul服务名</param>

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

        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;

            }

        }

2022沐雪.NetCore多租户商城系统源码https://muxue.blog.csdn.net/article/details/118370935?spm=1001.2014.3001.5502

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值