(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 多服务器交互,需要记忆他们的服务 ...
随机推荐
- 2.网络编程-udp
# 使用套接字发送udp数据import socket s = socket.socket(socket.AF_INET, SOCK_DGRAM) s.sendto(b"hello" ...
- 精通initramfs构建step by step
(一)hello world 一.initramfs是什么 在2.6版本的linux内核中,都包含一个压缩过的cpio格式 的打包文件.当内核启动时,会从这个打包文件中导出文件到内核的rootfs ...
- python常用模块之pickle
python1个json模块和1个pickle模块都是用于序列化的模块. 其中前文介绍过json模块.json模块只能序列化普通字符,比如字典.列表等.但是如果是函数呢?json其实是无法序列化的.这 ...
- SQL Server ->> DAC(Dedicated Administrator Connection)专用管理员连接
专用管理员连接是一种特殊的SQL Server服务器诊断性质的连接,用于在正常或者说标准连接形式无法连接SQL Server服务器的情况下连接到服务器进行服务器性能或者错误诊断.DAC同样支持安全加密 ...
- GPU与CPU的区别
作者:虫子君 链接:https://www.zhihu.com/question/19903344/answer/96081382 来源:知乎 著作权归作者所有.商业转载请联系作者获得授权,非商业转载 ...
- php二维数组去重
php二维数组去重 前言:php一维数组去重很简单,直接array_unique($arr)即可,但是二维数组去重就得自己去写了 二维数组去重方法: /* * 二维数组去重 * 注意:二维数组中的元素 ...
- Flask消息闪现
目录 Flask消息闪现 简单的例子 闪现消息的类别 过滤闪现消息 Message Flashing 参考 Flask消息闪现 一个好的应用和用户界面都需要良好的反馈.如果用户得不到足够的反馈,那么应 ...
- Linux 小知识翻译 - 「Linux」怎么读?
主要讨论日语中的读法,所以没有完全按照原文来翻译. 「linux」的读法有很多(这里指在日语中),代表性的读法有以下几种: A). 李纳苦思 B). 李奴苦思 C). 纳依纳苦思 A和B相同的是将 l ...
- [Tomcat]The JRE_HOME environment variable is not defined correctly
在tomcat的bin目录下,双击startup.bat,闪一下,就没了,后来仔细看了一下黑屏闪的内容如下: the JRE_HOME environment variable is not defi ...
- 对数组的操作splice() 和slice() 用法和区别
JavaScript splice() 方法 定义和用法 splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目. 注释:该方法会改变原始数组. 语法 arrayObject.spli ...