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. PAT甲级——1006 Sign In and Sign Out

    PATA1006 Sign In and Sign Out At the beginning of every day, the first person who signs in the compu ...

  2. 让Spring不再难懂-aop篇

    什么是aop AOP(Aspect-OrientedProgramming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP允许 ...

  3. Margin of Error|sample size and E

    8.3 Margin of Error 由该公式可知: To improve the precision of the estimate, we need to decrease the margin ...

  4. 手机安装fiddler证书

    如果电脑浏览器和手机抓包有证书问题,那就把电脑的证书都删除,然后在fiddler里重置,手机上删除不了单个证书,可以重新下载一个证书安装 如果电脑抓包正常,手机抓包不正常,那就手机重新下载证书安装 手 ...

  5. Qt foreach关键字用法

    Qt提供一个关键字 foreach (实际是 <QtGlobal> 里定义的一个宏)用于方便地访问容器里所有数据项. foreach 关键字用于遍历容路中所有的项,使用 foreach 的 ...

  6. 浏览器证书问题,chorm,ie,edge,safari都会去读系统证书,firefox例外

    坑爹 没想过浏览器兼容的问题. 为系统安装用户证书后, firefox一直无法连接 提示 连接 www.httpsserver.com:8985 时发生错误. SSL 对等端无法协商出一个可接受的安全 ...

  7. C#获取代码执行时间(精确到毫秒)

    private void Time(int i) { Stopwatch sw = new Stopwatch(); sw.Start(); Thread.Sleep(i); sw.Stop(); C ...

  8. jquery.Table实现的翻页功能比较完整漂亮,本想扩展个模版DIV

    jquery.dataTable实现的翻页功能比较完整漂亮,本想提取其的翻页部分,再结合模版DIV,bootstrop实现聊天记息的展示. jquery.Table 与table结合的较紧,不能在很下 ...

  9. 关于KMP算法的重大发现

    之前写KMP模板的时候,nx[i]代表最大的一个x,使s[1,x-1]是s[1,i-1]的后缀.(方法1) 然而网上还有另一种方法求nx数组,nx[i]表示最大的一个x,使s[1,x]是s[1,i]的 ...

  10. 安装 Kali Linux 2018.1 及之后的事

    本文为原创文章,转载请标明出处 目录 制作U盘启动盘 安装 Kali Linux 之后的事 更新源 配置 Zsh 配置 Vim 修改 Firefox 语言为中文 安装 Gnome 扩展 美化 安装 G ...