.Net5微服务之Consul通讯和负载均衡策略

下载Consul

地址:https://www.consul.io/downloads

运行Consul

我这里是windows,cd到目录下输入命令

.\consul.exe agent -dev

 

然后打开链接 http://127.0.0.1:8500/ 这样启动就完事了

 

在.Net项目中 通过Nuget安装Consul的.NET客户端

 install-package Consul

基于IApplicationBuilder写一个扩展方法,用于调用Consul API

using System;
using Consul;
using Microsoft.Extensions.Configuration;

namespace General.Mvc.Middleware
{
    public static class ConsulHelper
    {
        public static void ConsulRegist(this IConfiguration Configuration)
        {
            ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri(Configuration["ConsulUrl"]);
                c.Datacenter = "dc1";

            });
            string ip = string.IsNullOrEmpty(Configuration["ip"])?"127.0.0.1": Configuration["ip"];
            int port = Convert.ToInt32(Configuration["port"])==0?555: Convert.ToInt32(Configuration["port"]);
            int weight = Convert.ToInt32(Configuration["weight"]) == 0 ? 1 : Convert.ToInt32(Configuration["weight"]);
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID="service-"+Guid.NewGuid(),
                 Name="GeneralNetCore",
                 Address= Configuration["ServerIp"],//本服务公网ip
                 Port= port,
                 //Tags = null,
                 Tags = new string[] { weight.ToString() },
                 Check=new AgentServiceCheck()
                 {
                      Interval = TimeSpan.FromSeconds(10),
                      HTTP=$"http://{ip}:{port}/Home/HealthCheck",
                      Timeout=TimeSpan.FromSeconds(5), //检测等待时间
                      DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5) //失败多久过后移除
                 }
            });
        }

    }
}

 

在Starup类的Configure方法中,调用此扩展方法

 //consul
this.Configuration.ConsulRegist();

 

然后启动

dotnet run --urls="http://*:555" --ip=127.0.0.1 --port=555 --weight=1 --ConsulUrl="http://127.0.0.1:8500"

 

再访问Consul的界面端已经是注册服务了

 

如果需要删除某个注册的服务,

PUT请求访问 http://127.0.0.1:8500/v1/agent/service/deregister/{servicename}

获取Consul服务实例-均衡策略|轮训策略|权重策略

在外部定义 private static int iSeed = 0;

具体实现:

           ConsulClient client = new ConsulClient(c=> {
                c.Address = new Uri("http://127.0.0.1:8500/");
                c.Datacenter = "dc1";
            }); //找到Consul
            var dictionary = client.Agent.Services().Result.Response;

            string grounpName = "GeneralNetCore";

                var list = dictionary.Where(s=>s.Value.Service.Equals(grounpName,StringComparison.OrdinalIgnoreCase));
                //均衡策略
                //var item = list.ToArray()[new Random().Next(0,list.Count())];
                //轮训策略
                //var item = list.ToArray()[iSeed++ % list.Count()];
                //权重策略
                var pairsList = new List<KeyValuePair<string, AgentService>>();
                foreach (var pair in list)
                {
                    int count  = int.Parse(pair.Value.Tags?[0]);
                    for (int i = 0; i < count; i++)
                    {
                        pairsList.Add(pair);
                    }
                }
                var item = pairsList.ToArray()[new Random(iSeed++).Next(0, pairsList.Count())];

            return Ok(urlList);