三, .NET Core 微服务学习 ——客户端嵌入-Consul

Consul 示意图如下:

 

步骤:

1. 下载Consul, 并解压  下载地址:https://www.consul.io/downloads

2. 启动Consul, 使用命令行启动  consul.exe agent -dev    

 Consul 默认端口8500

 

 3. 在WebAPI添加注册代码

  a . Nuget 引用Consul 库

  b. 在服务的startup.cs 的Configure方法中添加注册代码

    this.Configuration.ConsulRegist();

        public static void ConsulRegist(this IConfiguration configuration)
        {
            ConsulClient client = new ConsulClient(c=>
            {
                c.Address = new Uri("http://localhost:8500");
                c.Datacenter = "dc2";
            });

            string ip = configuration["ip"];
            int port = int.Parse(configuration["ip"]); // 命令行必须传入参数
            int weight = string.IsNullOrEmpty(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]);

            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = ip + "-" + port, // 服务Id
                Name = "MicroService", // 组名称- Group
                Address = ip,  // IP地址
                Port = port, // 不同的实例
                Tags = new string[] { weight.ToString() }, // 标签
                Check = new AgentServiceCheck()
                {
                    Interval = TimeSpan.FromSeconds(12), // 间隔12s一次
                    HTTP = $"http://{ip}:{port}/api/Health/Index",  // 检测的请求
                    Timeout = TimeSpan.FromSeconds(5),  // 检测等待时间
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60) // 失败后多久移除服务
                }
            }) ;
        }

 

启动WebAPI服务

 

 Client端调用

            ConsulClient client = new ConsulClient(c=>
            {
                c.Address = new Uri("http://localhost:8500");
                c.Datacenter = "dc2";
            });
            var response = client.Agent.Services().Result.Response;

 

 

 

 

获取到URL地址集合之后就可以根据自己的需求进行调用,比如轮询,随机等

设置URL

            ConsulClient client = new ConsulClient(c=>
            {
                c.Address = new Uri("http://localhost:8500");
                c.Datacenter = "dc2";
            });
            var response = client.Agent.Services().Result.Response;

            url = "http://MicroService/api/users/all";

            Uri uri = new Uri(url);
            string groupName = uri.Host;
            AgentService agentService = null;
            var serviceDictionary = response.Where(s=>s.Value.Service.Equals(groupName, StringComparison.OrdinalIgnoreCase)).ToArray();
            {
                agentService = serviceDictionary[0].Value; // 获取第一个服务
            }
            url = $"{uri.Scheme}://{agentService.Address}:{agentService.Port}{uri.PathAndQuery}";
            #endregion
            content = InvokeAPI(url);

            ViewBag.Users = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<User>>(content);

运行结果:

负载均衡策略实现:

轮询:

        public IActionResult Index()
        {
            // 单体系统
            //ViewBag.Users = this._IUserService.UserAll();
            string url = String.Empty;
            string content = String.Empty;
            // WebAPI 调用
            //string url = "http://localhost:5726/api/users/all";
            //string content = InvokeAPI(url);

            // Nginx
            //url = "http://localhost:8087/api/users/all";

            #region Consul

            ConsulClient client = new ConsulClient(c=>
            {
                c.Address = new Uri("http://localhost:8500");
                c.Datacenter = "dc2";
            });
            var response = client.Agent.Services().Result.Response;

            url = "http://MicroService/api/users/all";

            Uri uri = new Uri(url);
            string groupName = uri.Host;
            AgentService agentService = null;

            var serviceDictionary = response.Where(s=>s.Value.Service.Equals(groupName, StringComparison.OrdinalIgnoreCase)).ToArray();
            {
                agentService = serviceDictionary[iIndex % serviceDictionary.Length].Value;
                iIndex++;
            }
            url = $"{uri.Scheme}://{agentService.Address}:{agentService.Port}{uri.PathAndQuery}";
            #endregion
            content = InvokeAPI(url);

            ViewBag.Users = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<User>>(content);
            return View();
        }

        private static int iIndex = 0;
View Code

平均策略:

// 平均策略
agentService = serviceDictionary[new Random(iIndex++).Next(0, serviceDictionary.Length)].Value;

权重:

思路:定义AgentService数组,根据不同权重往数组中添加数据,然后进行随机

 

posted @ 2020-07-02 15:11  沙漠狼  阅读(226)  评论(0编辑  收藏  举报