Consul搭建

基于Docker搭建Consul

以下为单机环境构建脚本,用于本机测试,生产环境中应当进行集群搭建

version: '3'
services:
consul:
image: consul:1.7.1
container_name: consul
volumes:
- /c/docker/consul/data:/consul/data
- /c/docker/consul:/consul/config
ports:
- 8300:8300
- 8301:8301
- 8301:8301/udp
- 8302:8302
- 8302:8302/udp
- 8400:8400
- 8500:8500
- 53:53/udp
command: agent -server -bind=0.0.0.0 -client=0.0.0.0 -node=consul_Server1 -bootstrap-expect=1 -ui

成功搭建后,访问8500端口,你可以看到如下界面

基于Windows搭建Consul

点击下载Consul

执行以下命令运行consul

consul agent -dev

ServiceA集成Consul做服务注册

配置前一篇文章中的ServiceA

Install-Package Consul -Version 0.7.2.6

  • Consul配置模型
public class ServiceDisvoveryOptions
{
public string ServiceName { get; set; } public ConsulOptions Consul { get; set; }
} public class ConsulOptions
{
public string HttpEndpoint { get; set; } public DnsEndpoint DnsEndpoint { get; set; }
} public class DnsEndpoint
{
public string Address { get; set; } public int Port { get; set; } public IPEndPoint ToIPEndPoint()
{
return new IPEndPoint(IPAddress.Parse(Address), Port);
}
}
  • 添加appsetting.json
  "ServiceDiscovery": {
"ServiceName": "ServiceA",
"Consul": {
"HttpEndpoint": "http://127.0.0.1:8500",
"DnsEndpoint": {
"Address": "127.0.0.1",
"Port": 8600
}
}
}
  • Consul服务注册实现
private void ConfigureConsul(IApplicationBuilder app, IOptions<ServiceDisvoveryOptions> serviceOptions, IConsulClient consul, IHostApplicationLifetime lifetime)
{
var features = app.Properties["server.Features"] as FeatureCollection;
var addresses = features.Get<IServerAddressesFeature>()
.Addresses
.Select(p => new Uri(p)); foreach (var address in addresses)
{
var serviceId = $"{serviceOptions.Value.ServiceName}_{address.Host}:{address.Port}"; var httpCheck = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1),
Interval = TimeSpan.FromSeconds(30),
HTTP = new Uri(address, "health").OriginalString
}; var registration = new AgentServiceRegistration()
{
Checks = new[] { httpCheck },
Address = address.Host,
ID = serviceId,
Name = serviceOptions.Value.ServiceName,
Port = address.Port
}; consul.Agent.ServiceRegister(registration).GetAwaiter().GetResult(); lifetime.ApplicationStopping.Register(() =>
{
consul.Agent.ServiceDeregister(serviceId).GetAwaiter().GetResult();
});
}
}
  • 配置服务到DI容器
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery")); services.AddSingleton<IConsulClient>(p => new ConsulClient(cfg =>
{
var serviceConfiguration = p.GetRequiredService<IOptions<ServiceDisvoveryOptions>>().Value; if (!string.IsNullOrEmpty(serviceConfiguration.Consul.HttpEndpoint))
{
// if not configured, the client will use the default value "127.0.0.1:8500"
cfg.Address = new Uri(serviceConfiguration.Consul.HttpEndpoint);
}
})); services.AddHealthChecks();
services.AddControllers();
}
  • 将Consul相关配置添加到管道
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions<ServiceDisvoveryOptions> serviceDisvoveryOptions, IConsulClient consul, IHostApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting(); app.UseAuthorization(); ConfigureConsul(app, serviceDisvoveryOptions, consul, lifetime); app.UseHealthChecks("/health"); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
  • 运行ServiceA



    可以看到健康检查已通过,并且服务ServiceA已成功注册到Consul

Ocelot集成Consul做服务发现

安装nuget包依赖

Install-Package Ocelot.Provider.Consul -Version 14.0.11

在上一篇文章的基础上,我们先修改ocelot.json

删除了ServiceA路由中的DownstreamHostAndPorts写死的地址和端口,改为使用Consul服务发现

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/{url}",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/service-a/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"AuthenticationOptions": {
"AuthenticationProviderKey": "SampleKey",
"AllowedScopes": [ "gateway_api" ]
},
"ServiceName": "ServiceA",
"LoadBalancerOptions": {
"Type": "LeastConnection"
}
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost",
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "Consul"
}
}
}

向容器中添加Consul服务

public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot()
.AddConsul();
}

启动各个服务,查看结果



可以看到已成功执行

更多参考

Consul

Service Discovery And Health Checks In ASP.NET Core With Consul

.NET微服务从0到1:服务注册与发现(Consul)的更多相关文章

  1. 分布式服务注册和发现consul 简要介绍

    Consul是HashiCorp公司推出的开源工具,用于实现分布式系统的服务发现与配置.与其他分布式服务注册与发现的方案,Consul的方案更"一站式",内置了服务注册与发现框 架 ...

  2. 微服务之服务注册与发现--Consul(转载)

    http://blog.csdn.net/buxiaoxia/article/details/69788114 https://www.cnblogs.com/xiaohanlin/p/8016803 ...

  3. 玩转springcloud(三):服务的提供者与调用者(注册于发现)

    一.简介 上文我们实践了cloud的注册中心的单服务于多节点的搭建,房子造好了得有人来住不是,这篇我们实践下服务提供者于调用者的案例,也就是服务端和客户端的调用. 本文会设计三个module:注册中心 ...

  4. 5.服务注册与发现Consul,简学API,手动注册和删除服务

    package main import ( httptransport "github.com/go-kit/kit/transport/http" mymux "git ...

  5. C#使用Consul集群进行服务注册与发现

    前言 我个人觉得,中间件的部署与使用是非常难记忆的:也就是说,如果两次使用中间件的时间间隔比较长,那基本上等于要重新学习使用. 所以,我觉得学习中间件的文章,越详细越好:因为,这对作者而言也是一份珍贵 ...

  6. 温故知新,.Net Core遇见Consul(HashiCorp),实践分布式服务注册与发现

    什么是Consul 参考 https://www.consul.io https://www.hashicorp.com 使用Consul做服务发现的若干姿势 ASP.NET Core 发布之后通过命 ...

  7. 基于.NET CORE微服务框架 -谈谈surging的服务容错降级

    一.前言 对于不久开源的surging受到不少.net同学的青睐,也受到.net core学习小组的关注,邀请加入.NET China Foundation以方便国内.net core开源项目的推广, ...

  8. .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现

    Tip: 此篇已加入.NET Core微服务基础系列文章索引 =>  Steeltoe目录快速导航: 1. 基于Steeltoe使用Spring Cloud Eureka 2. 基于Steelt ...

  9. 微服务(Microservices)和服务网格(Service Mesh)架构概念整理

    注:文章内容为摘录性文字,自己阅读的一些笔记,方便日后查看. 微服务(Microservices) 在过去的 2016 年和 2017 年,微服务技术迅猛普及,和容器技术一起成为这两年中最吸引眼球的技 ...

随机推荐

  1. CentOS-DHCP服务搭建

    title date tags layout CentOS6.5 DHCP服务器搭建 2018-08-26 Centos6.5服务器搭建 post 1.安装dhcp软件包 yum install -y ...

  2. Office Lens:口袋中的扫描仪

    Lens:口袋中的扫描仪" title="Office Lens:口袋中的扫描仪"> 编者按:开会时,你是否觉得白板上天马行空的讨论记录誊抄起来费时费事又难以共享- ...

  3. Kinect_V1在Debian testing的配置指北

    在Linux下驱动Kinect V1现在有两种方式,一种是使用OpenNI + SensorKinect + Nite的方案,一种是使用OpenNI2 + libfreenect的方案,第一种我没有尝 ...

  4. [LC] 122. Best Time to Buy and Sell Stock II

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  5. [LC] 28. Implement strStr()

    Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle ...

  6. 20180105关于课题所用的labview的改进随笔

    在原有的工程上1.写入60个不同的数字~顶层,看测量次数是1.2.3.4.5.6.7.8.9的时候文件记到几次的数,一次的话,从接受命令到全部写到文件最短需要等多久.写入固定的数,通过startfla ...

  7. python3爬虫:利用urllib与有道翻译获得翻译结果

    在实现这一功能时遇到了一些困难,由于按照<零基础入门python>中的代码无法实现翻译,会爆出“您的请求来源非法,商业用途使用请关注有道翻译API官方网站“有道智云”: http://ai ...

  8. TortoiseSVN配置和使用教程

    2009-04-24 来源:dev.idv.tw 1 安装及下载client 端 2 什么是SVN(Subversion)? 3 为甚么要用SVN? 4 怎么样在Windows下面建立SVN Repo ...

  9. 在Oracle Spatial中增加Web Mercator投影坐标系

    参考资料: 1. 最重要的参考文章,基本上就是按这个做的!!!:https://www.inf.unibz.it/dis/wiki/doku.php?id=students:minnerebner:o ...

  10. java实现树的一般操作

    https://www.cnblogs.com/dawnyxl/p/9047437.html 树是数据结构中最基本的结构,今天的博客更新一下树的基本操作: 树的节点结构: package tree; ...