微服务学习.net5+consul

趁着刚过完年,还没有开始做业务的时候,学习下consul 概念自己去官网看,这里只讲下具体实现

官网下载https://www.consul.io/downloads 我下载的是Windows版本

启动consul命令 

consul agent -dev -client 0.0.0.0

新建.net5的api项目,.net5直接默认是swagger

4.新建扩展服务注册到Consul方法,ConsulExtenions.cs

 public static void ConsulRegist(this IConfiguration configuration)
        {
            try
            {
                string ip = configuration["ip"];
                string port = configuration["port"];
                string weight = configuration["weight"];
                string consulAddress = configuration["ConsulAddress"];
                string consulCenter = configuration["ConsulCenter"];

                ConsulClient client = new ConsulClient(c =>
                {
                    c.Address = new Uri(consulAddress);
                    c.Datacenter = consulCenter;
                });

                client.Agent.ServiceRegister(new AgentServiceRegistration()
                {
                    ID = "CommService" + Guid.NewGuid(),//--唯一的
                    Name = "CommService",//分组---根据Service
                    Address = ip,
                    Port = int.Parse(port),
                    Tags = new string[] { weight.ToString() },//额外标签信息
                    Check = new AgentServiceCheck()
                    {
                        Interval = TimeSpan.FromSeconds(12),
                        HTTP = $"http://{ip}:{port}/Api/Health/Index", // 给到200
                        Timeout = TimeSpan.FromSeconds(5),
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
                    }//配置心跳
                });
                Console.WriteLine($"{ip}:{port}--weight:{weight}"); //命令行参数获取
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Consul注册:{ex.Message}");
            }
        }

ip port 配置在appsettings.json里面

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ip": "localhost",
  "port": 5000,
  "weight": 1,
  "ConsulAddress": "http://127.0.0.1:8500",
  "ConsulCenter": "dc1"
}

Startup注册ConsulRegist方法

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "comm.api v1"));
            //}

            //   app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            // Consul注册
            this.Configuration.ConsulRegist();
        }

可以用dotnet 启动2个comm.api.dll  端口号自己随便取,我取的5000和6000 HealthController为配置的心跳api返回的结果

再来看下Consul 会发现多了CommService

2 Instances为端口号5000和6000的api

注册完成了,接下来实现调用看效果图

调用代码

 public static AgentService ChooseService(string serviceName)
        {
            using (ConsulClient client = new ConsulClient(c => c.Address = new Uri("http://localhost:8500")))
            {
                var services = client.Agent.Services().Result.Response;
                // 找出目标服务
                var targetServices = services.Where(c => c.Value.Service.Equals(serviceName)).Select(s => s.Value);
                // 实现随机负载均衡
                var targetService = targetServices.ElementAt(new Random().Next(1, 1000) % targetServices.Count());
                Console.WriteLine($"{DateTime.Now} 当前调用服务为:{targetService.Address}:{targetService.Port}");

                return targetService;
            }
        }
  public string GetCommUrl()
        {
            AgentService agentService = ConsulClientExtenions.ChooseService("CommService");
            string url = $"http://{agentService.Address}:{agentService.Port}/api/Comm/GetProvince";
            return url;
        }

需要demo的留言

原文地址:https://www.cnblogs.com/panjuan/p/14434827.html