zoukankan      html  css  js  c++  java
  • 微服务学习.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的留言

  • 相关阅读:
    selenium Grid2 分布式自动化测试环境搭建
    Python Appium 开启Android测试之路
    C#导出数据到CSV和EXCEL文件时数字文本被转义的解决方法
    浅谈 DML、DDL、DCL的区别
    让EntityFramework6支持SQLite
    System.Drawing.Color的颜色对照表
    清除远程桌面连接记录和SQLSERVER 连接记录的办法
    Jquery操作select选项集合!
    asp.net 模拟CURL调用微信公共平台API 上传下载多媒体文件接口
    Log4net 根据日志类别保存到不同的文件,并按照日期生成不同文件名称
  • 原文地址:https://www.cnblogs.com/panjuan/p/14434827.html
Copyright © 2011-2022 走看看