首页 > 其他分享 >使用Consul搭建负载均衡

使用Consul搭建负载均衡

时间:2023-09-24 18:45:35浏览次数:45  
标签:负载 服务 string dictionary int Consul new 搭建

一、Consul服务注册发现

  1.启动Consul :consul agent -dev

    2.打开Consul地址,默认8500端口:8500

    3.封装静态类,注册Consul服务的方法:

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


    public static class ConsulHelper
    {
      /// <summary>
      /// Consul注册
      /// </summary>
      /// <param name="configuration"></param>
      public static void ConsulRegist(this IConfiguration configuration)
      {
        ConsulClient client = new ConsulClient(c =>
        {
          c.Address = new Uri("http://localhost:8500/");
          c.Datacenter = "dc1";
        });//找到consul
        string ip = string.IsNullOrWhiteSpace(configuration["ip"]) ? "192.168.3.230" : configuration["ip"];
        int port = int.Parse(configuration["port"]);//命令行参数必须传入
        int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]);
        client.Agent.ServiceRegister(new AgentServiceRegistration()
        {
          ID = "service" + Guid.NewGuid(),//注册的服务ID
          Name = "TestService",//Group--分组
          Address = 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(120)//失败后多久移除
          }
        });
        //命令行参数获取
        Console.WriteLine($"注册成功:{ip}:{port}--weight:{weight}");
      }
    }

  4.在Startup.cs文件或者Program.cs文件总注册服务:   

    //初始化一次
    app.Configuration.ConsulRegist();

  5.设置健康检测的控制服务  

    app.MapWhen(context => context.Request.Path.Equals("/Api/Health/Index"),
    applicationBuilder => applicationBuilder.Run(async context =>
    {
      Console.WriteLine($"This is Health Check");
      context.Response.StatusCode = (int)HttpStatusCode.OK;
      await context.Response.WriteAsync("OK");
    }));

 

二、前端服务的发现与调用

    private static int iIndex = 0;//暂不考虑线程安全

 

 

    #region Consul服务注册发现
    //consul获取服务--得知道Consul服务中的服务组名和API函数名
    string url = null;
    url = "http://ZhaoxiService/api/users/all";//Consul服务中的服务组名和API函数名

 

    ConsulClient client = new ConsulClient(c =>
    {
      c.Address = new Uri("http://localhost:8500/");
      c.Datacenter = "dc1";
    });//找到consul--像DNS
    var response = client.Agent.Services().Result.Response;//获取服务清单

 

 

    Uri uri = new Uri(url);
    string groupName = uri.Host;
    AgentService agentService = null;
    var dictionary = response.Where(s => s.Value.Service.Equals(groupName, StringComparison.OrdinalIgnoreCase)).ToArray();

    

    ////默认使用第一个注册的服务,无意义
    {
      //agentService = dictionary[0].Value;  
    }

 

    ////轮询策略 也是平均,但是太僵硬了
     {
      //agentService = dictionary[iIndex++ % dictionary.Length].Value;
    }

 

    ////平均策略--随机获取索引--相对就平均
    {
      //agentService = dictionary[new Random(iIndex++).Next(0, dictionary.Length)].Value;
    }

 

    //权重:3个实例能力不同,承担的压力也要不同
    {
      List<KeyValuePair<string, AgentService>> pairsList = new List<KeyValuePair<string, AgentService>>();
      foreach (var pair in dictionary)
      {
        int count = int.Parse(pair.Value.Tags?[0]);//1 5 10
         for (int i = 0; i < count; i++)
        {
          pairsList.Add(pair);
        }
      }
      //16个
      agentService = pairsList.ToArray()[new Random(iIndex++).Next(0, pairsList.Count())].Value;
    }

 


    url = $"{uri.Scheme}://{agentService.Address}:{agentService.Port}{uri.PathAndQuery}";
    string content = InvokeApi(url);
    base.ViewBag.Users = JsonConvert.DeserializeObject<IEnumerable<User>>(content);
    Console.WriteLine($"This is {url} Invoke");
    #endregion

 

标签:负载,服务,string,dictionary,int,Consul,new,搭建
From: https://www.cnblogs.com/jiangyuhu/p/17726402.html

相关文章

  • 109_博客搭建进阶篇
    这是一篇原发布于2020-01-1709:43:00得益小站的文章,备份在此处。前言本文接《0基础小白向博客搭建指南》[postcid="18"/]本文均以阿里云举例更改面板端口相信大家登录面板的时候都看到了这个提示,为了我们服务器的安全我们还是要把宝塔端口改一下。1.打开阿里云云服务的......
  • 使用Nginx搭建负载均衡
    1.修改配置文件conf/nginx.conf      2.配置文件中增加服务调用upstreamNET6RC2{server127.0.0.1:5726;server127.0.0.1:5727;server127.0.0.1:5728;server127.0.0.1:5729;}server{......
  • kali搭建DVWA踩的坑
    在网上看视频安装DVWA的时候还是遇到了很多问题,这里截取部分新手问题,提出解决方法,避免踩坑。kali搭建LAMP安装apacheaptinstallapache2-y设置开机自启动按q退出安装mysqlaptinstallmariadb-server-y同样设置开机自启安装phpapt-yinstallphp7/0php-pearlibap......
  • 一、简易搭建本地CAS服务端
    CAS服务端war包下载https://repo1.maven.org/maven2/org/apereo/cas/cas-server-webapp-tomcat/5.3.14/可使用迅雷下载cas-server-webapp-tomcat-5.3.14.war,速度很快将wab包放到本地tomcat的webapps下D:\tomcat\apache-tomcat-8.5.63\webapps\cas\WEB-INF\classes\servic......
  • JMeter 分布式集群远程压测及搭建常见问题
    1、JMeter可以在以下场景下使用分布式远程压测:性能测试:JMeter可以模拟大量用户并发访问,进行性能测试。当需要模拟成千上万的用户请求时,单台机器可能无法承受如此大的负载,此时可以使用分布式远程压测来将测试负载分发到多台机器上,提高测试的效率和准确性。稳定性测试:在一段时间......
  • Redis搭建集群架构
    使用docker搭建6.x版本以后的镜像docker支持部署集群模式,由于Redis要求集群至少要有三个主节点,因此本次测试搭建了三主三从的Redis集群。不基于Host网络模式配置docker-compose.yml文件version:"3"networks:redis-cluster:driver:bridgeipam:......
  • Redis搭建哨兵模式架构
    使用Docker安装因为配置太复杂,所以这里我们使用dockercompose来一键部署不使用内部网络搭建编写redis主从docker-compose.ymlversion:'3'services:master:image:rediscontainer_name:redis-masterrestart:alwayscommand:redis-server--requi......
  • Linux轻松搭建网站:安装Apache服务攻略
    在如今数字化时代,网站已成为企业宣传和信息传递的重要渠道。而Apache服务器则是众多网站服务中最为常用的一种。本文将详细介绍如何在Linux系统上安装Apache服务,帮助你轻松搭建自己的网站。1.确认Linux版本在开始安装Apache服务之前,需要确认你所使用的Linux版本。常见的Linux发......
  • centos apache 如何在CentOS操作系统上搭建ApacheWeb服务器??
    在今天的互联网时代sogoupinyinlinux,Web服务器已经成为了企业和个人建立网站的重要基础设施之一。而在众多的Web服务器软件中,Apache绝对是最受欢迎和广泛使用的开源Web服务器之一。而在CentOS操作系统上搭建Apache服务器,不仅可以提供高效的性能和稳定性,还可以免费获得高质量的技......
  • 搭建Wpf框架(17) ——大文件上传与下载
    先上效果图:大文件上传1.客户端需要按照块拆成一块一块,先计算大小,然后计算块的个数,然后按块逐个上传,代码如下:public async Task<UploadResult> UploadFileChunck(string path, Action<double> progressAction)        {            try      ......