.NET微服务从0到1:服务注册与发现(Consul)
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)的更多相关文章
- 分布式服务注册和发现consul 简要介绍
Consul是HashiCorp公司推出的开源工具,用于实现分布式系统的服务发现与配置.与其他分布式服务注册与发现的方案,Consul的方案更"一站式",内置了服务注册与发现框 架 ...
- 微服务之服务注册与发现--Consul(转载)
http://blog.csdn.net/buxiaoxia/article/details/69788114 https://www.cnblogs.com/xiaohanlin/p/8016803 ...
- 玩转springcloud(三):服务的提供者与调用者(注册于发现)
一.简介 上文我们实践了cloud的注册中心的单服务于多节点的搭建,房子造好了得有人来住不是,这篇我们实践下服务提供者于调用者的案例,也就是服务端和客户端的调用. 本文会设计三个module:注册中心 ...
- 5.服务注册与发现Consul,简学API,手动注册和删除服务
package main import ( httptransport "github.com/go-kit/kit/transport/http" mymux "git ...
- C#使用Consul集群进行服务注册与发现
前言 我个人觉得,中间件的部署与使用是非常难记忆的:也就是说,如果两次使用中间件的时间间隔比较长,那基本上等于要重新学习使用. 所以,我觉得学习中间件的文章,越详细越好:因为,这对作者而言也是一份珍贵 ...
- 温故知新,.Net Core遇见Consul(HashiCorp),实践分布式服务注册与发现
什么是Consul 参考 https://www.consul.io https://www.hashicorp.com 使用Consul做服务发现的若干姿势 ASP.NET Core 发布之后通过命 ...
- 基于.NET CORE微服务框架 -谈谈surging的服务容错降级
一.前言 对于不久开源的surging受到不少.net同学的青睐,也受到.net core学习小组的关注,邀请加入.NET China Foundation以方便国内.net core开源项目的推广, ...
- .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现
Tip: 此篇已加入.NET Core微服务基础系列文章索引 => Steeltoe目录快速导航: 1. 基于Steeltoe使用Spring Cloud Eureka 2. 基于Steelt ...
- 微服务(Microservices)和服务网格(Service Mesh)架构概念整理
注:文章内容为摘录性文字,自己阅读的一些笔记,方便日后查看. 微服务(Microservices) 在过去的 2016 年和 2017 年,微服务技术迅猛普及,和容器技术一起成为这两年中最吸引眼球的技 ...
随机推荐
- rest framework-分页-长期维护
############### 分页组件 ############### # 分页组件 # # django也有分页,rest framework也有分页,但是没有页面这个概念了, # 这个分页 ...
- TreeviewEditor.rar
本工具可以打开.保存指定格式的XML文件. 树形控件的节点可以编辑.删除.增加.使用本工具看方便地创建书或论文的目录大纲,我用这个工具已经写了好几本书了. 动态图1: 动态图2:编辑效果,支持节点拖曳 ...
- socket握手SYN和ACK理解
ACK 英文缩写: ACK (ACKnowledge Character) 中文译名: 确认字符 分类: 传输与接入 解释: 在数据通信传输中,接收站发给发送站的一种传输控制字符.它表示确认发来的数据 ...
- cesium初探之加载三维模型
项目需要用到二三维地图切换,本来准备研究ArcGIS js for Web 3d,但考虑到版权的问题,决定试着用cesium来做,于是花了2天时间抱着试试看的心态把cesium从环境配置到加载三维模型 ...
- 《C程序设计语言》练习1-10
#include<stdio.h> main() { int c; c=getchar(); while (c !=EOF) { if (c=='\t') { c='\\'; putcha ...
- Zabbix 监控sqlserver
转:Zabbix 监控sqlserver 一:Zabbix监控sqlserver 方法一: 1.思路整理 1.在zabbix server上安装Freetds.unixODBC.unixODBC-de ...
- The file named error_log is too large
The file named errorlog is too large */--> The file named errorlog is too large 1 Problem One day ...
- PCIe的事务传输层的处理(TLP)
主要从以下几个方面解决: 1.TLP基本的概念: 2.寻址定位与路由导向 3.请求和响应机制 4.虚拟通道机制 5.数据完整性 6.i/o,memory,configuration,message r ...
- [LC] 359. Logger Rate Limiter
Design a logger system that receive stream of messages along with its timestamps, each message shoul ...
- jprofiler监控tomcat
jprofiler监控tomcat https://www.cnblogs.com/yjd_hycf_space/p/7727757.html https://www.jianshu.com/p/c3 ...