.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 年,微服务技术迅猛普及,和容器技术一起成为这两年中最吸引眼球的技 ...
随机推荐
- linux 上zookeeper安装
一.zookeeper 的安装及配置 .Zookeeper下载 wget http://mirror.bit.edu.cn/apache/zookeeper/zookeeper-3.3.6/zooke ...
- 谈谈有关 Python 的GIL 和 互斥锁
转载:https://blog.csdn.net/Amberdreams/article/details/81274217 有 Python 开发经验的人也许听说过这样一句话:Python 不能充分利 ...
- python+selenium自动化测试之登录
selenium_login.py import unittest from selenium import webdriver class LoginTest(unittest.TestCase): ...
- ROS中的日志(log)消息
学会使用日志(log)系统,做ROS大型项目的主治医生 通过显示进程的运行状态是好的习惯,但需要确定这样做不会影响到软件的运行效率和输出的清晰度.ROS 日志 (log) 系统的功能就是让进程生成一些 ...
- getRandomInt getRandomString
import java.util.concurrent.ThreadLocalRandom; private static final String AB = "ABCDEFGHIJKLMN ...
- django项目总结_20191128
django项目总结_20191128 ##################### 1,这个项目分为四个部分: 用户模块 商品模块 购物车模块 订单模块 2,这个项目用到的技术: redis cele ...
- confidence intervals and precision|The One-Mean z-Interval Procedure|When to Use the One-Mean z-Interval Procedure
Confidence Intervals for One Population Mean When σ Is Known Obtaining Confidence Intervals for a Po ...
- ASP.NET ASHX 一般处理程序教程
你不想创建一个普通ASP.NET的Web窗体页.而又要通过一个查询字符串返回一个动态的图片.XML或者非HTML网页.这是一个用C#编程语言编写的使用ASHX(一般处理程序)的简单教程. 简介 首先, ...
- Java IO: 其他字节流(上)
作者: Jakob Jenkov 译者: 李璟(jlee381344197@gmail.com) 本小节会简要概括Java IO中的PushbackInputStream,SequenceInputS ...
- 93)PHP,session代码练习
(1)开启session Session_start(): (2)session值的设定: <?php session_start(); $_SESSION['name']='xiaohua'; ...