上一章说了  Consul服务注册  现在我要连接上Consul里面的服务 请求它们的API接口 应该怎么做呢?

1.找Consul要一台你需要的服务器

1.1 获取Consul下的所有注册的服务

using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500")))
{
   var services = consulClient.Agent.Services().Result.Response;
   foreach(var service in services.Values)
     {
       Console.WriteLine($"id={service.ID},name={service.Service},ip={service.Address},port={service.Port}");
     }
} 

1.2 随机取一个Name为MsgService的服务


下面的代码使用当前 TickCount 进行取模的方式达到随机获取一台服务器实例的效果,这叫做“客户端负载均衡”: 
using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500")))
{
     var services = consulClient.Agent.Services().Result.Response.Values.Where(s => s.Service.Equals("MsgService", StringComparison.OrdinalIgnoreCase));       if(!services.Any())
     {
          Console.WriteLine("找不到服务的实例");
     }
     else
     {
          var service = services.ElementAt(Environment.TickCount%services.Count());
          Console.WriteLine($"{service.Address}:{service.Port}");
     }
}
当然在一个毫秒之类会所有请求都压给一台服务器,基本就够用了。也可以自己写随机、轮询等客户端负载均衡算法,也可以自己实现按不同权重分配(注册时候 Tags 带上配置、权重等信息)等算法。 

2.请求服务器的接口

你拿到了http地址  难道还不会请求接口么   找个httphelper  直接请求就好了  如果还是不会 就来群里问吧  群号:608188505

给大家上一个 我常用的httphelper 可能被我该的不像样了  不过相信大家都会用  不会的话 来群里找我吧。

 using System;
 using System.Collections.Generic;
 using System.Diagnostics;
 using System.IO;
 using System.IO.Compression;
 using System.Linq;
 using System.Net;
 using System.Net.Security;
 using System.Runtime.InteropServices;
 using System.Security.Cryptography.X509Certificates;
 using System.Text;
 using System.Text.RegularExpressions;
 using System.Threading.Tasks;

 namespace ClientApp
 {/// <summary>
  /// Http连接操作帮助类
  /// </summary>
     public class HttpHelper
     {
         ;
         //编码
         private Encoding _encoding = Encoding.Default;
         //浏览器类型
         private string[] _useragents = new string[]{
             "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
             "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)",
             "Mozilla/5.0 (Windows NT 6.1; rv:36.0) Gecko/20100101 Firefox/36.0",
             "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0"
         };

         private String _useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36";
         //接受类型
         private String _accept = "text/html, application/xhtml+xml, application/xml, */*";
         //超时时间
          * ;
         //类型
         private string _contenttype = "application/x-www-form-urlencoded";
         //cookies
         private String _cookies = "";
         //cookies
         private CookieCollection _cookiecollection;
         //custom heads
         private Dictionary<string, string> _headers = new Dictionary<string, string>();

         public HttpHelper()
         {
             _headers.Clear();
             //随机一个useragent
             _useragent = _useragents[, _useragents.Length)];
             //解决性能问题?
             ServicePointManager.DefaultConnectionLimit = ConnectionLimit;
         }

         public void InitCookie()
         {
             _cookies = "";
             _cookiecollection = null;
             _headers.Clear();
         }

         /// <summary>
         /// 设置当前编码
         /// </summary>
         /// <param name="en"></param>
         public void SetEncoding(Encoding en)
         {
             _encoding = en;
         }

         /// <summary>
         /// 设置UserAgent
         /// </summary>
         /// <param name="ua"></param>
         public void SetUserAgent(String ua)
         {
             _useragent = ua;
         }

         public void RandUserAgent()
         {
             _useragent = _useragents[, _useragents.Length)];
         }

         public void SetCookiesString(string c)
         {
             _cookies = c;
         }

         /// <summary>
         /// 设置超时时间
         /// </summary>
         /// <param name="sec"></param>
         public void SetTimeOut(int msec)
         {
             _timeout = msec;
         }

         public void SetContentType(String type)
         {
             _contenttype = type;
         }

         public void SetAccept(String accept)
         {
             _accept = accept;
         }

         /// <summary>
         /// 添加自定义头
         /// </summary>
         /// <param name="key"></param>
         /// <param name="ctx"></param>
         public void AddHeader(String key, String ctx)
         {
             //_headers.Add(key,ctx);
             _headers[key] = ctx;
         }

         /// <summary>
         /// 清空自定义头
         /// </summary>
         public void ClearHeader()
         {
             _headers.Clear();
         }

         /// <summary>
         /// 获取HTTP返回的内容
         /// </summary>
         /// <param name="response"></param>
         /// <returns></returns>
         private String GetStringFromResponse(HttpWebResponse response)
         {
             String html = "";
             try
             {
                 Stream stream = response.GetResponseStream();
                 StreamReader sr = new StreamReader(stream, Encoding.UTF8);
                 html = sr.ReadToEnd();

                 sr.Close();
                 stream.Close();
             }
             catch (Exception e)
             {
                 Trace.WriteLine("GetStringFromResponse Error: " + e.Message);
             }

             return html;
         }

         /// <summary>
         /// 检测证书
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="certificate"></param>
         /// <param name="chain"></param>
         /// <param name="errors"></param>
         /// <returns></returns>
         private bool CheckCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
         {
             return true;
         }

         /// <summary>
         /// 发送GET请求
         /// </summary>
         /// <param name="url"></param>
         /// <returns></returns>
         public String HttpGet(String url)
         {
             return HttpGet(url, url);
         }

         /// <summary>
         /// 发送GET请求
         /// </summary>
         /// <param name="url"></param>
         /// <param name="refer"></param>
         /// <returns></returns>
         public String HttpGet(String url, String refer)
         {
             String html;
             try
             {
                 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckCertificate);
                 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                 request.UserAgent = _useragent;
                 request.Timeout = _timeout;
                 request.ContentType = _contenttype;
                 request.Accept = _accept;
                 request.Method = "GET";
                 request.Referer = refer;
                 request.KeepAlive = true;
                 request.AllowAutoRedirect = true;
                 request.UnsafeAuthenticatedConnectionSharing = true;
                 request.CookieContainer = new CookieContainer();
                 //据说能提高性能
                 //request.Proxy = null;
                 if (_cookiecollection != null)
                 {
                     foreach (Cookie c in _cookiecollection)
                     {
                         c.Domain = request.Host;
                     }

                     request.CookieContainer.Add(_cookiecollection);
                 }

                 foreach (KeyValuePair<String, String> hd in _headers)
                 {
                     request.Headers[hd.Key] = hd.Value;
                 }

                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                 html = GetStringFromResponse(response);
                 if (request.CookieContainer != null)
                 {
                     response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                 }

                 if (response.Cookies != null)
                 {
                     _cookiecollection = response.Cookies;
                 }
                 if (response.Headers["Set-Cookie"] != null)
                 {
                     string tmpcookie = response.Headers["Set-Cookie"];
                     _cookiecollection.Add(ConvertCookieString(tmpcookie));
                 }

                 response.Close();
                 return html;
             }
             catch (Exception e)
             {
                 Trace.WriteLine("HttpGet Error: " + e.Message);
                 return String.Empty;
             }
         }

         /// <summary>
         /// 获取MINE文件
         /// </summary>
         /// <param name="url"></param>
         /// <returns></returns>
         public Byte[] HttpGetMine(String url)
         {
             Byte[] mine = null;
             try
             {
                 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckCertificate);
                 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                 request.UserAgent = _useragent;
                 request.Timeout = _timeout;
                 request.ContentType = _contenttype;
                 request.Accept = _accept;
                 request.Method = "GET";
                 request.Referer = url;
                 request.KeepAlive = true;
                 request.AllowAutoRedirect = true;
                 request.UnsafeAuthenticatedConnectionSharing = true;
                 request.CookieContainer = new CookieContainer();
                 //据说能提高性能
                 request.Proxy = null;
                 if (_cookiecollection != null)
                 {
                     foreach (Cookie c in _cookiecollection)
                         c.Domain = request.Host;
                     request.CookieContainer.Add(_cookiecollection);
                 }

                 foreach (KeyValuePair<String, String> hd in _headers)
                 {
                     request.Headers[hd.Key] = hd.Value;
                 }

                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                 Stream stream = response.GetResponseStream();
                 MemoryStream ms = new MemoryStream();

                 ];
                 while (true)
                 {
                     , b.Length);
                     ms.Write(b, , s);
                      || s < b.Length)
                     {
                         break;
                     }
                 }
                 mine = ms.ToArray();
                 ms.Close();

                 if (request.CookieContainer != null)
                 {
                     response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                 }

                 if (response.Cookies != null)
                 {
                     _cookiecollection = response.Cookies;
                 }
                 if (response.Headers["Set-Cookie"] != null)
                 {
                     _cookies = response.Headers["Set-Cookie"];
                 }

                 stream.Close();
                 stream.Dispose();
                 response.Close();
                 return mine;
             }
             catch (Exception e)
             {
                 Trace.WriteLine("HttpGetMine Error: " + e.Message);
                 return null;
             }
         }

         /// <summary>
         /// 发送POST请求
         /// </summary>
         /// <param name="url"></param>
         /// <param name="data"></param>
         /// <returns></returns>
         public String HttpPost(String url, String data)
         {
             return HttpPost(url, data, url,null);
         }

         /// <summary>
         /// 发送POST请求
         /// </summary>
         /// <param name="url"></param>
         /// <param name="data"></param>
         /// <param name="refer"></param>
         /// <returns></returns>
         public String HttpPost(String url, String data, String refer,string cookie)
         {
             String html;
             try
             {
                 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckCertificate);
                 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                 request.UserAgent = _useragent;
                 request.Timeout = _timeout;
                 request.Referer = refer;
                 request.ContentType = _contenttype;
                 request.Accept = _accept;
                 request.Method = "POST";
                 request.KeepAlive = true;
                 request.AllowAutoRedirect = true;

                 request.CookieContainer = new CookieContainer();
                 if (!string.IsNullOrEmpty(cookie))
                 {
                     _cookiecollection = this.ConvertCookieString(cookie);
                 }
                 //据说能提高性能
                 request.Proxy = null;

                 if (_cookiecollection != null)
                 {
                     foreach (Cookie c in _cookiecollection)
                     {
                         c.Domain = request.Host;
                         )
                             c.Domain = c.Domain.Remove(c.Domain.IndexOf(':'));
                     }
                     request.CookieContainer.Add(_cookiecollection);
                 }

                 foreach (KeyValuePair<String, String> hd in _headers)
                 {
                     request.Headers[hd.Key] = hd.Value;
                 }
                 byte[] buffer = _encoding.GetBytes(data.Trim());
                 request.ContentLength = buffer.Length;
                 request.GetRequestStream().Write(buffer, , buffer.Length);
                 request.GetRequestStream().Close();

                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                 html = GetStringFromResponse(response);
                 if (request.CookieContainer != null)
                 {
                     response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                 }
                 if (response.Cookies != null)
                 {
                     _cookiecollection = response.Cookies;
                 }
                 if (response.Headers["Set-Cookie"] != null)
                 {
                     string tmpcookie = response.Headers["Set-Cookie"];
                     _cookiecollection.Add(ConvertCookieString(tmpcookie));
                 }

                 response.Close();
                 return html;
             }
             catch (Exception e)
             {
                 Trace.WriteLine("HttpPost Error: " + e.Message);
                 return String.Empty;
             }
         }

         public string UrlEncode(string str)
         {
             StringBuilder sb = new StringBuilder();
             byte[] byStr = _encoding.GetBytes(str);
             ; i < byStr.Length; i++)
             {
                 sb.Append());
             }

             return (sb.ToString());
         }

         /// <summary>
         /// 转换cookie字符串到CookieCollection
         /// </summary>
         /// <param name="ck"></param>
         /// <returns></returns>
         private CookieCollection ConvertCookieString(string ck)
         {
             CookieCollection cc = new CookieCollection();
             string[] cookiesarray = ck.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
             ; i < cookiesarray.Length; i++)
             {
                 string[] cookiesarray_2 = cookiesarray[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                 ; j < cookiesarray_2.Length; j++)
                 {
                     string[] cookiesarray_3 = cookiesarray_2[j].Trim().Split("=".ToCharArray());
                     )
                     {
                         ].Trim();
                         ].Trim();
                         if (cname.ToLower() != "domain" && cname.ToLower() != "path" && cname.ToLower() != "expires")
                         {
                             Cookie c = new Cookie(cname, cvalue);
                             cc.Add(c);
                         }
                     }
                 }
             }

             return cc;
         }

         public void DebugCookies()
         {
             Trace.WriteLine("**********************BEGIN COOKIES*************************");
             foreach (Cookie c in _cookiecollection)
             {
                 Trace.WriteLine(c.Name + "=" + c.Value);
                 Trace.WriteLine("Path=" + c.Path);
                 Trace.WriteLine("Domain=" + c.Domain);
             }
             Trace.WriteLine("**********************END COOKIES*************************");
         }

     }
 }

Httphelper

小哥哥 小姐姐们 如果本篇文章对你们有帮助的话 就点点右下角的推荐吧 0.0

(4)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Consul服务发现和消费的更多相关文章

  1. 酷学习笔记——ASP.NET Core 简介

    ASP.NET Core 简介 其实就是说酷好,不好好学,不学好,没饭吃. 新词汇:IoT,Internet of Things,网联网,微软物联网英文网站.微软物联网中文网站

  2. 【新书推荐】《ASP.NET Core微服务实战:在云环境中开发、测试和部署跨平台服务》 带你走近微服务开发

    <ASP.NET Core 微服务实战>译者序:https://blog.jijiechen.com/post/aspnetcore-microservices-preface-by-tr ...

  3. ASP.NET Core 微服务初探[1]:服务发现之Consul

    ASP.NET Core 微服务初探[1]:服务发现之Consul   在传统单体架构中,由于应用动态性不强,不会频繁的更新和发布,也不会进行自动伸缩,我们通常将所有的服务地址都直接写在项目的配置文件 ...

  4. 在ASP.NET Core Web API中为RESTful服务增加对HAL的支持

    HAL(Hypertext Application Language,超文本应用语言)是一种RESTful API的数据格式风格,为RESTful API的设计提供了接口规范,同时也降低了客户端与服务 ...

  5. Docker学习笔记之--.Net Core应用容器通过网桥连接Redis容器(环境:centos7)

    上节演示通过应用容器连接sql server容器,连接:Docker学习笔记之--.Net Core项目容器连接mssql容器(环境:centos7) 本节演示安装 redis容器,通过网桥连接 先决 ...

  6. 在 asp.net core 中使用类似 Application 的服务

    在 asp.net core 中使用类似 Application 的服务 Intro 在 asp.net 中,我们可以借助 Application 来保存一些服务器端全局变量,比如说服务器端同时在线的 ...

  7. .NET Core微服务实施之Consul服务发现与治理

    .NET Core微服务实施之Consul服务发现与治理   Consul官网:https://www.consul.io Consul下载地址:https://www.consul.io/downl ...

  8. ASP.NET Core在Azure Kubernetes Service中的部署和管理

    目录 ASP.NET Core在Azure Kubernetes Service中的部署和管理 目标 准备工作 注册 Azure 账户 AKS文档 进入Azure门户(控制台) 安装 Azure Cl ...

  9. 如何在ASP.NET Core中使用Azure Service Bus Queue

    原文:USING AZURE SERVICE BUS QUEUES WITH ASP.NET CORE SERVICES 作者:damienbod 译文:如何在ASP.NET Core中使用Azure ...

  10. (8)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Ocelot网关(Api GateWay)

    说到现在现有微服务的几点不足: 1) 对于在微服务体系中.和 Consul 通讯的微服务来讲,使用服务名即可访问.但是对于手 机.web 端等外部访问者仍然需要和 N 多服务器交互,需要记忆他们的服务 ...

随机推荐

  1. Git 学习一

    刚刚接触git,学习现骨干操作并记录一下过程中的小问题(Windows下) 1.新建git目录 创建一个目录,使用命令 git init 2.添加文件  git add a.txt 3.提交文件  g ...

  2. [20171110]sql语句相同sql_id可以不同吗.txt

    [20171110]sql语句相同sql_id可以不同吗.txt --//提一个问题,就是sql语句相同sql_id可以不同吗?--//使用dbms_shared_pool.markhot就可以做到. ...

  3. Java——语句

    空语句: ; 符合语句:{} if语句:if () {} else {} break 语句:跳出单层循环 循环语句:for(;;){}   do{}while()

  4. centos7安装rabbitmq 总结

    centos7下安装rabbitmq 折腾了三天最后做了以下总结 先查看一电脑名  :示例 #hostname name 查看一下hosts配置文件:如果如下结果,就要修改下 #cat /etc/ho ...

  5. linux 下正则匹配时间命名格式的文件夹

    用正则表达式匹配时间格式命名的文件夹 ls mypath | grep -E "[0-9]{4}-[0-9]{1,2}" mypath为需要查询的目录 查询出来的文件夹格式为:例 ...

  6. 13LaTeX学习系列之---LaTeX插入表格

    目录 目录 前言 (一)插入表格的基础语法 1.说明 2.源代码 3.输出效果 (二)查看文档 目录 本系列是有关LaTeX的学习系列,共计19篇,本章节是第13篇. 前一篇:12LaTeX学习系列之 ...

  7. java操作elasticsearch实现基本的增删改查操作

    一.在进行java操作elasticsearch之前,请确认好集群的名称及对应的ES节点ip和端口 1.查看ES的集群名称 #进入elasticsearch.yml配置文件/opt/elasticse ...

  8. 个人技术博客(a)

  9. PostgreSQL 空间处理函数

    PostGIS中的常用函数 以下内容包括比较多的尖括号,发布到blogger的时候会显示不正常,内容太多我也无暇一个个手动改代码,因此如有问题就去参考PostGIS官方文档. 首先需要说明一下,这里许 ...

  10. centos7下安装docker(13docker存储)

    Docker为容器提供了两种存放数据的资源: 1.storage driver管理的镜像层和容器层 2.Data volume Storage driver 之前我们学习镜像的时候知道镜像的分层结构: ...