(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 多服务器交互,需要记忆他们的服务 ...
随机推荐
- json替换jsonp实现跨域请求
最近遇到h5前端页面和web后端双方的请求存在跨域,普通的jquery.ajax请求已不能实现(因为js是不允许跨域的(如果可以跨域,那就能随便改别人的网页了),js的原理), 最后经过艰苦奋斗,终于 ...
- 简单整理关于C#和Java的区别
相信每个程序猿都有自己最喜欢的编程语言,然而对于编程语言似乎形成一条独特的鄙视链,就如Java和C#常常两边的开发者都是相互鄙视,然后他们一起共同鄙视全世界最好的编程语言——PHP 哈哈,但是其实我想 ...
- jenkins离线插件安装--笨方法
Jenkins离线安装插件有多种方式:代理or离线导入,但离线导入可能会存在版本差异或依赖的插件文件导致异常发生), 以下为笨方法但会很准确的解决以上的问题. 同版本Jenkins在线下载:模糊掉的是 ...
- SQL Server 2017数据库服务和SSMS图形化工具的的安装
第一章 SQL数据库服务的安装 1. 首先要加载sql2017数据库镜像,可以用虚拟光驱或是刻录光盘装载.执行setup.exe. 双击.exe文件 双击.exe文件 2. 选择安装-->全新s ...
- php解决前后端验证字符串长度不一致
前端代码 function getStrleng(str){ var myLen =0; for(var i=0;i<str.length;i++){ if(str.charCodeAt(i)& ...
- fedora更新
先换源再更新,否则等的太久,如果已经开始了直接ctrl+c取消 # dnf update
- 如何轻松搞定 笔记本搜不到WIFI信号问题
经常用电脑的同志肯定遇到过:一开机,发现右下角网络图标有个×号,wifi信号也搜不到:或者其他wifi信号能搜到,唯独自家的搜不到,是不是感觉很绝望啊,居然被wifi欺负到身上了,这也太憋屈了吧. 此 ...
- February 8th, 2018 Week 6th Thursday
When you fall in love, friends, let yourself fall. 当你坠入爱河,我的朋友,你就放手去爱吧. To love someone is like movi ...
- java集合类List
1.List Vector:线程安全的. ArrayList:适合查找与顺序添加. LinkedList:适合随机插入与删除. 1.1ArrayList与LinkedList的add添加 1.1.1A ...
- [bug]android monkey命令在Android N和Android O上的一点差异发现
最近再调试这个统计FPS的代码,发现代码在android N上可以正常运行,但在android O上却运行不了,拼了命的报错,给出的提示就是 ZeroDivisionError: division b ...