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. 腾讯云 Serverless 首发 1ms 计费粒度,立省 70% 费用

    云函数 SCF 采用按需付费的方式,并首次发布 1ms 计费粒度,真正实现按使用多少计算能力来计费. 云函数(Serverless Cloud Function,SCF)是腾讯云为企业和开发者们提供的 ...

  2. 头次接触wamp服务器、xampp,初次单独使用tomcat部署

    刚刚经过了近两天的接触wamp.xampp.tomcat的时光,真的爽 导师有个网站打不开了,就让我去弄,还有一个网站的后台密码忘了,让我帮忙找回来.我第一感觉就是第一个活不简单,第二个还不简单吗?打 ...

  3. 导出Wireless组中的成员

    get-adgroupmember -Identity wireless  |export-csv -path C:\Group.csv -Encoding UTF8

  4. python学习笔记(5)数据类型-字典

    字典是另一种可变容器模型,且可存储任意类型对象. 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示: d ...

  5. 第一课 安装wamp环境

    1.准备 怎样选择PHP的版本 IIS 如果想使用IIS配置PHP的话,那么需要选择Non-Thread Safe(NTS)版本的PHP Apache 如果你是用的Apache的版本来自Apache ...

  6. 《你不知道的Javascript》学习笔记

    简介 众所周知,JavaScript 既是一门充满吸引力.简单易用的语言,又是一门具有许多复杂微妙技术的语言,即使是经验丰富的JavaScript 开发者,如果没有认真学习的话也无法真正理解它们. 如 ...

  7. 《内蒙古自治区第十二届大学生程序设计竞赛试题_D: 正品的概率》

    问题 D: 正品的概率 内存限制:128 MB时间限制:1 S标准输入输出 题目类型:传统评测方式:文本比较上传者:外部导入 提交:36通过:7 返回比赛提交提交记录 题目描述 袋中有m枚正品硬币,n ...

  8. MOOC(4)- setup和teardown函数

    import unittest class TestRequest(unittest.TestCase): @classmethod def setUpClass(cls): print(" ...

  9. haproxy笔记之三:配置HAProxy详细介绍

    2.1 配置文件格式 HAProxy的配置处理3类来主要参数来源:——最优先处理的命令行参数,——“global”配置段,用于设定全局配置参数:——proxy相关配置段,如“defaults”.“li ...

  10. SWUST OJ NBA Finals(0649)

    NBA Finals(0649) Time limit(ms): 1000 Memory limit(kb): 65535 Submission: 404 Accepted: 128   Descri ...