本文介绍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. Spring 注解无效 空指针异常

    对于Java开发,现在Spring已成为一种生态,使用Spring成为一种享受,Spring的使用让开发变得更加便捷. 而Spring好用归好用,若不清楚里面的工作原理,使用的时候难免会踩到一些坑. ...

  2. kvm批量创建虚拟主机

    1.首先你的提前创建一个kvm虚拟机主机,才能批量复制创建 批量复制已经安装好的系统盘 `;.img centos7-$i.img && echo $i ;done 批量复制已经安装好 ...

  3. File "/usr/bin/pip", line 11, in <module> sys.exit(__main__._main()) AttributeError: 'module' object has no attribute '_main'

    多个版本pip共存导致 直接使用pip2进行安装即可 如:pip2 install requests

  4. Educational Codeforces Round 73 (Rated for Div. 2) B. Knights(构造)

    链接: https://codeforces.com/contest/1221/problem/B 题意: You are given a chess board with n rows and n ...

  5. CodeForces 835C - Star sky | Codeforces Round #427 (Div. 2)

    s <= c是最骚的,数组在那一维开了10,第八组样例直接爆了- - /* CodeForces 835C - Star sky [ 前缀和,容斥 ] | Codeforces Round #4 ...

  6. java8 time计算时间差

    最近使用Java8编写代码时,需要计算时间差,现整理如下 前言 本次使用了Java8提供的ChronoUnit工具类,它主要提供以下几种时间维度 枚举 枚举 说明 NANOS 毫微秒(毫秒的10000 ...

  7. msyql round函数隐藏问题

    1.背景 在用mysql round进行四舍五入计算的时候如果参与计算的字段为float,则最终计算出的四舍五入效果会有很大出入.例子我就不列举了 2.原因 mysql官方文档中关于ROUND函数的部 ...

  8. Python: 关于 sys.stdout.flush()

    stackoverflow https://stackoverflow.com/questions/10019456/usage-of-sys-stdout-flush-method Python's ...

  9. AGC029C - Lexicographic constraints

    记录我心路历程吧,这道小水题暴露出我很多问题. 给定 \(n\) 个字符串长度 \(a_i\) ,求字符集最小多大,才能构造出按字典序比较 \(s_1 < s_2 < \dots < ...

  10. vueApp打包

    本地打包测试 http-server是一个基于node.js的简单的,零配置的命令行http服务器.安装:npm install http-server -g使用:http-server [path] ...