(4)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Consul服务发现和消费
上一章说了 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服务发现和消费的更多相关文章
- 酷学习笔记——ASP.NET Core 简介
ASP.NET Core 简介 其实就是说酷好,不好好学,不学好,没饭吃. 新词汇:IoT,Internet of Things,网联网,微软物联网英文网站.微软物联网中文网站
- 【新书推荐】《ASP.NET Core微服务实战:在云环境中开发、测试和部署跨平台服务》 带你走近微服务开发
<ASP.NET Core 微服务实战>译者序:https://blog.jijiechen.com/post/aspnetcore-microservices-preface-by-tr ...
- ASP.NET Core 微服务初探[1]:服务发现之Consul
ASP.NET Core 微服务初探[1]:服务发现之Consul 在传统单体架构中,由于应用动态性不强,不会频繁的更新和发布,也不会进行自动伸缩,我们通常将所有的服务地址都直接写在项目的配置文件 ...
- 在ASP.NET Core Web API中为RESTful服务增加对HAL的支持
HAL(Hypertext Application Language,超文本应用语言)是一种RESTful API的数据格式风格,为RESTful API的设计提供了接口规范,同时也降低了客户端与服务 ...
- Docker学习笔记之--.Net Core应用容器通过网桥连接Redis容器(环境:centos7)
上节演示通过应用容器连接sql server容器,连接:Docker学习笔记之--.Net Core项目容器连接mssql容器(环境:centos7) 本节演示安装 redis容器,通过网桥连接 先决 ...
- 在 asp.net core 中使用类似 Application 的服务
在 asp.net core 中使用类似 Application 的服务 Intro 在 asp.net 中,我们可以借助 Application 来保存一些服务器端全局变量,比如说服务器端同时在线的 ...
- .NET Core微服务实施之Consul服务发现与治理
.NET Core微服务实施之Consul服务发现与治理 Consul官网:https://www.consul.io Consul下载地址:https://www.consul.io/downl ...
- ASP.NET Core在Azure Kubernetes Service中的部署和管理
目录 ASP.NET Core在Azure Kubernetes Service中的部署和管理 目标 准备工作 注册 Azure 账户 AKS文档 进入Azure门户(控制台) 安装 Azure Cl ...
- 如何在ASP.NET Core中使用Azure Service Bus Queue
原文:USING AZURE SERVICE BUS QUEUES WITH ASP.NET CORE SERVICES 作者:damienbod 译文:如何在ASP.NET Core中使用Azure ...
- (8)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Ocelot网关(Api GateWay)
说到现在现有微服务的几点不足: 1) 对于在微服务体系中.和 Consul 通讯的微服务来讲,使用服务名即可访问.但是对于手 机.web 端等外部访问者仍然需要和 N 多服务器交互,需要记忆他们的服务 ...
随机推荐
- Node 编码规范(优秀是一种习惯)
编码规范 空格与格式 1. 缩进 采用2个空格缩进,而不是tab缩进. 空格在编辑器中与字符是等宽的,而tab可能因编辑器的设置不同.2个空格会让代码看起来更紧凑.明快. 2. 变量声明 永远用var ...
- Django2.0.1开发框架搭建
1.使用vs2017创建空白django项目 2.右键python环境的env---安装python包 升级django到2.0.1和setuptools到38.4.0版本,具体环境如下: 3.配置 ...
- MyEclipse10或者eclipse中配置开发Python的Pydev插件安装教程
注意使用LiClipse的用户 PyDev已经预装在LiClipse中,所以可以跳过这一步(请注意,如果使用LiClipse,PyDev不能单独安装或更新,因为它必须始终作为一个整体更新). 必需品 ...
- SQL易错总结1
SQL易错总结1 进阶 select语句.select * 查询所有不规范,写出要查的属性.distinct慎用,性能消耗很大 like 模糊查询 ,空值判断是 is null 单行函数:lower( ...
- 【PAT】B1058 选择题(20 分)
这道题的逻辑怪复杂的,写起来蛮费时间的 结构体中要储存的信息多,整体不难,信息量大,容易把人搞蒙 #include<stdio.h> #include<string.h> #i ...
- Python之对象的永久保存模块---pickle
经常遇到在Python程序运行中得到了一些字符串.列表.字典等数据,想要长久的保存下来,方便以后使用,而不是简单的放入内存中关机断电就丢失数据. 这个时候Pickle模块就派上用场了,它可以将对象转换 ...
- nginx代理 upstream轮询
问题描述 我有2个Tomcat 一个端口开启(8021),一个端口未开启(8022),在nginx里用upstream模块进行代理 ,代理的负载算法采用的是默认的轮询算法,配置成功后,访问页面时并没 ...
- MySQL基本简单操作03
MySQL基本简单操作 现在我创建了一个数据表,表的内容如下: mysql> select * from gubeiqing_table; +----------+-----+ | name | ...
- python随机生成6位数验证码
#随机生成6位数验证码 import randomcode = []for i in range(6): if i == str(random.randint(1,5)): cod ...
- Java中的HashMap源码记录以及并发环境的几个问题
HashMap源码简单分析: 1 一切需要从HashMap属性字段说起: /** The default initial capacity - MUST be a power of two. 初始容量 ...