本文介绍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: '')
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后台界面
或者打开另一个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
至此,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: '')
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,效果图如下
可以看到,多次请求依次访问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