.Netcore 2.0 Ocelot Api网关教程(4)- 服务发现

本文介绍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.jsonCount_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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259

推荐阅读更多精彩内容