本文介绍Ocelot中的服务发现(Service Discovery),Ocelot允许指定一个服务发现提供器,之后将从中寻找下游服务的host和port来进行请求路由。
关于服务发现的详细介绍请点击
在Ocelot中使用了Consul作为服务发现的provider。

1、Consul下载安装

官方下载页选择合适的平台下载,解压出一个二进制文件并保存到相应位置,并将路径存入path中,本文以windows版本为例(其他平台操作类似)。
打开 cmd/powershell 运行 consul agent -dev 输出如下文本表示成功以dev方式启动consul

==> Starting Consul agent...
==> Consul agent running!
Version: 'v1.0.7'
Node ID: '3fc1edca-b635-56cc-b767-01a942423f73'
Node name: 'Weidaicheng-PC'
Datacenter: 'dc1' (Segment: '<all>')
Server: true (Bootstrap: false)
Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, DNS: 8600)
Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false ==> Log data will now stream in as it occurs: 2018/04/29 09:22:03 [DEBUG] agent: Using random ID "3fc1edca-b635-56cc-b767-01a942423f73" as node ID
2018/04/29 09:22:03 [INFO] raft: Initial configuration (index=1): [{Suffrage:Voter ID:3fc1edca-b635-56cc-b767-01a942423f73 Address:127.0.0.1:8300}]
2018/04/29 09:22:03 [INFO] raft: Node at 127.0.0.1:8300 [Follower] entering Follower state (Leader: "")
2018/04/29 09:22:03 [INFO] serf: EventMemberJoin: Weidaicheng-PC.dc1 127.0.0.1
2018/04/29 09:22:03 [INFO] serf: EventMemberJoin: Weidaicheng-PC 127.0.0.1
2018/04/29 09:22:03 [INFO] consul: Adding LAN server Weidaicheng-PC (Addr: tcp/127.0.0.1:8300) (DC: dc1)
2018/04/29 09:22:03 [INFO] consul: Handled member-join event for server "Weidaicheng-PC.dc1" in area "wan"
2018/04/29 09:22:03 [INFO] agent: Started DNS server 127.0.0.1:8600 (udp)
2018/04/29 09:22:03 [INFO] agent: Started DNS server 127.0.0.1:8600 (tcp)
2018/04/29 09:22:03 [INFO] agent: Started HTTP server on 127.0.0.1:8500 (tcp)
2018/04/29 09:22:03 [INFO] agent: started state syncer
2018/04/29 09:22:03 [WARN] raft: Heartbeat timeout from "" reached, starting election
2018/04/29 09:22:03 [INFO] raft: Node at 127.0.0.1:8300 [Candidate] entering Candidate state in term 2
2018/04/29 09:22:03 [DEBUG] raft: Votes needed: 1
2018/04/29 09:22:03 [DEBUG] raft: Vote granted from 3fc1edca-b635-56cc-b767-01a942423f73 in term 2. Tally: 1
2018/04/29 09:22:03 [INFO] raft: Election won. Tally: 1
2018/04/29 09:22:03 [INFO] raft: Node at 127.0.0.1:8300 [Leader] entering Leader state
2018/04/29 09:22:03 [INFO] consul: cluster leadership acquired
2018/04/29 09:22:03 [INFO] consul: New leader elected: Weidaicheng-PC
2018/04/29 09:22:03 [DEBUG] consul: Skipping self join check for "Weidaicheng-PC" since the cluster is too small
2018/04/29 09:22:03 [INFO] consul: member 'Weidaicheng-PC' joined, marking health alive
2018/04/29 09:22:03 [DEBUG] agent: Skipping remote check "serfHealth" since it is managed automatically
2018/04/29 09:22:03 [INFO] agent: Synced node info
2018/04/29 09:22:03 [DEBUG] agent: Node info in sync
2018/04/29 09:22:04 [DEBUG] agent: Skipping remote check "serfHealth" since it is managed automatically
2018/04/29 09:22:04 [DEBUG] agent: Node info in sync

浏览器输入http://localhost:8500可以看到UI后台界面

 
Consul UI.png

或者打开另一个PowerShell输入 consul members 输出如下

Node            Address         Status  Type    Build  Protocol  DC   Segment
Weidaicheng-PC 127.0.0.1:8301 alive server 1.0.7 2 dc1 <all>

至此,Consul安装完成

2、代码修改

继续使用上一篇的项目,在WebApiA和WebApiB中分别新建一个api控制器 CounterController 代码如下

//WebApiA
using Microsoft.AspNetCore.Mvc; namespace WebApiA.Controllers
{
[Produces("application/json")]
[Route("api/[controller]/[action]")]
public class CounterController : Controller
{
private static int _count = 0; [HttpGet]
public string Count()
{
return $"Count {++_count} from WebapiA";
}
}
}
//WebApiB
using Microsoft.AspNetCore.Mvc; namespace WebApiB.Controllers
{
[Produces("application/json")]
[Route("api/[controller]/[action]")]
public class CounterController : Controller
{
private static int _count = 0; [HttpGet]
public string Count()
{
return $"Count {++_count} from WebapiB";
}
}
}

修改OcelotGetway项目中的配置文件 configuration.json
在 ReRoutes 节点中添加

{
"DownstreamPathTemplate": "/api/Counter/Count",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/count",
"UpstreamHttpMethod": [ "Get" ],
"ServiceName": "Count",
"LoadBalancer": "RoundRobin",
"UseServiceDiscovery": true
}

其中,ServiceName指定服务发现的服务名称,在之后Consul中注册服务的时候会用到,LoadBalancer指定使用的负载均衡模式(目前Ocelot仅支持时间片轮询(RoundRobin)和最少连接(LeastConnection)模式),UseServiceDiscovery标志使用服务发现。
注:如果不指定负载均衡,将不使用负载均衡,本文中使用时间片轮询为例。
然后再根节点添加全局配置

"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500
}
}

指定服务发现提供器的位置。目前Ocelot只支持共用一个provider。

3、注册服务

在consul所在的目录下创建文件夹 consul.d,文件夹位置及文件夹名称可以随意,进入consul.d文件夹中创建两个json文件 Count_1.json 和 Count_2.json,分别添加如下文本

{
"service": {
"id": "count1",
"name": "Count",
"tags": ["dev"],
"address": "localhost",
"port": 5001
}
}
{
"service": {
"id": "count2",
"name": "Count",
"tags": ["dev"],
"address": "localhost",
"port": 5002
}
}

以第一个为例,注册一个服务id为count1,服务名称为Count,和之前配置中使用的相同,还有地址和端口。
使用 Ctrl+C 关闭正在运行的consul,然后输入 consul agent -dev -config-dir=C:/consul_1.0.7/consul.d 其中 C:/consul_1.0.7/consul.d 是本机的配置文件路径。
可以看到如下输出

==> Starting Consul agent...
==> Consul agent running!
Version: 'v1.0.7'
Node ID: '91af5002-a1d6-409e-e36b-f7a081f84d24'
Node name: 'Weidaicheng-PC'
Datacenter: 'dc1' (Segment: '<all>')
Server: true (Bootstrap: false)
Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, DNS: 8600)
Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false ==> Log data will now stream in as it occurs: 2018/04/29 09:41:38 [DEBUG] agent: Using random ID "91af5002-a1d6-409e-e36b-f7a081f84d24" as node ID
2018/04/29 09:41:38 [INFO] raft: Initial configuration (index=1): [{Suffrage:Voter ID:91af5002-a1d6-409e-e36b-f7a081f84d24 Address:127.0.0.1:8300}]
2018/04/29 09:41:38 [INFO] raft: Node at 127.0.0.1:8300 [Follower] entering Follower state (Leader: "")
2018/04/29 09:41:38 [INFO] serf: EventMemberJoin: Weidaicheng-PC.dc1 127.0.0.1
2018/04/29 09:41:38 [INFO] serf: EventMemberJoin: Weidaicheng-PC 127.0.0.1
2018/04/29 09:41:38 [INFO] consul: Adding LAN server Weidaicheng-PC (Addr: tcp/127.0.0.1:8300) (DC: dc1)
2018/04/29 09:41:38 [INFO] consul: Handled member-join event for server "Weidaicheng-PC.dc1" in area "wan"
2018/04/29 09:41:38 [INFO] agent: Started DNS server 127.0.0.1:8600 (udp)
2018/04/29 09:41:38 [INFO] agent: Started DNS server 127.0.0.1:8600 (tcp)
2018/04/29 09:41:38 [INFO] agent: Started HTTP server on 127.0.0.1:8500 (tcp)
2018/04/29 09:41:38 [INFO] agent: started state syncer
2018/04/29 09:41:38 [WARN] raft: Heartbeat timeout from "" reached, starting election
2018/04/29 09:41:38 [INFO] raft: Node at 127.0.0.1:8300 [Candidate] entering Candidate state in term 2
2018/04/29 09:41:38 [DEBUG] raft: Votes needed: 1
2018/04/29 09:41:38 [DEBUG] raft: Vote granted from 91af5002-a1d6-409e-e36b-f7a081f84d24 in term 2. Tally: 1
2018/04/29 09:41:38 [INFO] raft: Election won. Tally: 1
2018/04/29 09:41:38 [INFO] raft: Node at 127.0.0.1:8300 [Leader] entering Leader state
2018/04/29 09:41:38 [INFO] consul: cluster leadership acquired
2018/04/29 09:41:38 [INFO] consul: New leader elected: Weidaicheng-PC
2018/04/29 09:41:38 [DEBUG] consul: Skipping self join check for "Weidaicheng-PC" since the cluster is too small
2018/04/29 09:41:38 [INFO] consul: member 'Weidaicheng-PC' joined, marking health alive
2018/04/29 09:41:39 [DEBUG] agent: Skipping remote check "serfHealth" since it is managed automatically
2018/04/29 09:41:39 [INFO] agent: Synced service "count1"
2018/04/29 09:41:39 [INFO] agent: Synced service "count2"
2018/04/29 09:41:39 [DEBUG] agent: Node info in sync
2018/04/29 09:41:39 [DEBUG] agent: Service "count1" in sync
2018/04/29 09:41:39 [DEBUG] agent: Service "count2" in sync
2018/04/29 09:41:39 [DEBUG] agent: Node info in sync
2018/04/29 09:41:39 [DEBUG] agent: Skipping remote check "serfHealth" since it is managed automatically
2018/04/29 09:41:39 [DEBUG] agent: Service "count1" in sync
2018/04/29 09:41:39 [DEBUG] agent: Service "count2" in sync
2018/04/29 09:41:39 [DEBUG] agent: Node info in sync

在倒数第三行和倒数第二行可以看到count1和count2的两个服务注册成功,使用postman/浏览器请求一下http://localhost:8500/v1/catalog/service/count
可以看到注册的两个Count服务的信息

[
{
"ID": "91af5002-a1d6-409e-e36b-f7a081f84d24",
"Node": "Weidaicheng-PC",
"Address": "127.0.0.1",
"Datacenter": "dc1",
"TaggedAddresses": {
"lan": "127.0.0.1",
"wan": "127.0.0.1"
},
"NodeMeta": {
"consul-network-segment": ""
},
"ServiceID": "count1",
"ServiceName": "Count",
"ServiceTags": [
"dev"
],
"ServiceAddress": "localhost",
"ServiceMeta": {},
"ServicePort": 5001,
"ServiceEnableTagOverride": false,
"CreateIndex": 6,
"ModifyIndex": 6
},
{
"ID": "91af5002-a1d6-409e-e36b-f7a081f84d24",
"Node": "Weidaicheng-PC",
"Address": "127.0.0.1",
"Datacenter": "dc1",
"TaggedAddresses": {
"lan": "127.0.0.1",
"wan": "127.0.0.1"
},
"NodeMeta": {
"consul-network-segment": ""
},
"ServiceID": "count2",
"ServiceName": "Count",
"ServiceTags": [
"dev"
],
"ServiceAddress": "localhost",
"ServiceMeta": {},
"ServicePort": 5002,
"ServiceEnableTagOverride": false,
"CreateIndex": 7,
"ModifyIndex": 7
}
]

4、运行与结果查看

分别运行WebApiA、WebApiB、OcelotGatway三个项目,多次请求http://localhost:5000/Count,效果图如下

 
count.gif

可以看到,多次请求依次访问A、B、A......正是时间片轮询的负载均衡模式。

源码下载

完,下一篇介绍认证和授权

参考链接

https://blog.csdn.net/mr_seaturtle_/article/details/77618403
http://ocelot.readthedocs.io/en/latest/features/servicediscovery.html
https://www.consul.io/intro/getting-started/install.html

 
 

9人点赞

 
Ocelot

 
 

作者:Weidaicheng
链接:https://www.jianshu.com/p/05a1bf2545a0
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

.Netcore 2.0 Ocelot Api网关教程(4)- 服务发现的更多相关文章

  1. .Netcore 2.0 Ocelot Api网关教程(2)- 路由

    .Netcore 2.0 Ocelot Api网关教程(1) 路由介绍 上一篇文章搭建了一个简单的Api网关,可以实现简单的Api路由,本文介绍一下路由,即配置文件中ReRoutes,ReRoutes ...

  2. .Netcore 2.0 Ocelot Api网关教程(6)- 配置管理

    本文介绍Ocelot中的配置管理,配置管理允许在Api网关运行时动态通过Http Api查看/修改当前配置.由于该功能权限很高,所以需要授权才能进行相关操作.有两种方式来认证,外部Identity S ...

  3. .Netcore 2.0 Ocelot Api网关教程(7)- 限流

    本文介绍Ocelot中的限流,限流允许Api网关控制一段时间内特定api的总访问次数.限流的使用非常简单,只需要添加配置即可. 1.添加限流 修改 configuration.json 配置文件,对  ...

  4. .Netcore 2.0 Ocelot Api网关教程(10)- Headers Transformation

    本文介绍Ocelot中的请求头传递(Headers Transformation),其可以改变上游request传递给下游/下游response传递给上游的header. 1.修改ValuesCont ...

  5. .Netcore 2.0 Ocelot Api网关教程(5)- 认证和授权

    本文介绍Ocelot中的认证和授权(通过IdentityServer4),本文只使用最简单的IdentityServer,不会对IdentityServer4进行过多讲解. 1.Identity Se ...

  6. .Netcore 2.0 Ocelot Api网关教程(1)- 入门

    Ocelot(Github)Ocelot官方文档(英文)本文不会介绍Api网关是什么以及Ocelot能干什么需要对Api网关及Ocelot有一定的理论了解 开始使用Ocelot搭建一个入门级Api网关 ...

  7. .Netcore 2.0 Ocelot Api网关教程(3)- 路由聚合

    在实际的应用当中,经常会遇到同一个操作要请求多个api来执行.这里先假设一个应用场景:通过姓名获取一个人的个人信息(性别.年龄),而获取每种个人信息都要调用不同的api,难道要依次调用吗?在Ocelo ...

  8. .Netcore 2.0 Ocelot Api网关教程(9)- QoS

    本文介绍Ocelot中的QoS(Quality of Service),其使用了Polly对超时等请求下游失败等情况进行熔断. 1.添加Nuget包 添加 Ocelot.Provider.Polly  ...

  9. .Netcore 2.0 Ocelot Api网关教程(8)- 缓存

    Ocelot中使用 CacheManager 来支持缓存,官方文档中强烈建议使用该包作为缓存工具.以下介绍通过使用CacheManager来实现Ocelot缓存. 1.通过Nuget添加 Ocelot ...

随机推荐

  1. RHEL6 学习:使用 cryptsetup 给分区加密

    RHEL6 学习:使用 cryptsetup 给分区加密 今天学习了 RHEL 对硬盘分区加密的知识,在 RHEL 系统里可以通过使用 cryptsetup 工具对硬盘分区进行加密,加密后的分区需要输 ...

  2. spark为什么比hadoop的mr要快?

    1.前言 Spark是基于内存的计算,而Hadoop是基于磁盘的计算:Spark是一种内存计算技术. 但是事实上,不光Spark是内存计算,Hadoop其实也是内存计算. Spark和Hadoop的根 ...

  3. 在laravel5.8中集成swoole组件----初步测试

    铺垫 前提是先安装swoole组件,我采用从pecl-----php扩展组件网下载swoole扩展包,然后切入到解压缩的扩展包中运行phpize命令, phpize是一种编译命令,可以在安装文件中生成 ...

  4. 置换的玩笑——DFS&&暴力

    题目 链接 题意:一个$1$到$n$的序列被去掉空格,需要将其还原.例如$4111109876532$可还原成$4 \ 1 \  11 \  10 \  9 \  8 \  7 \  6 \  5 \ ...

  5. Java日期工具类DateUtils详解(转)

    jar包 appache下的 common-lang3 一. 对指定的日期新增年.月.周.日.小时.分钟.秒.毫秒 public static Date addDays(Date date, int ...

  6. Can't install '*' from pristine store, because no checksum is recorded for this file

    svn同步时,提示clean up,但clean up 时提示: Error:Error performing cleanup for 'E:\project\projectProjectIDEA\b ...

  7. Luogu P2516 [HAOI2010]最长公共子序列 DP

    首先$LIS$显然:$f[i][j]=max(f[i][j-1],f[i-1][j],(a[i]==b[j])*f[i-1][j-1])$ 考虑如何转移数量: 首先,不管$a[i]$是否等于$b[j] ...

  8. 【Android】查看内存

      [文章来源]http://blog.csdn.net/hudashi/article/details/7050897 查看内存使用的方式有很多种,但是各个方式查看到的结果可能会有微略不同. 方式一 ...

  9. CPU结构及段地址偏移地址的概念

    原文地址:http://blog.csdn.net/yihuiworld/article/details/7533335#comments 程序如何执行: CPU先找到程序在内存中的入口地址 -- 地 ...

  10. 2019ICPC陕西邀请赛复盘

    题目链接:The 2019 ACM-ICPC China Shannxi Provincial Programming Contest A:签到,按花费时间从小到大排个序 #include<cs ...