一.概述

  ocelot允许指定服务发现提供程序,如consul或eureka。 这二个中间件是用来实现:服务治理或秒服务发现,服务发现查找ocelot正在转发请求的下游服务的主机和端口。目前ocelot仅在globalconfiguration部分支持配置服务发现功能,这意味着相同的服务发现提供程序将用于为reroute级别指定servicename的所有reroutes。这里介绍下服务发现的二个中间件:consul与eureka。

  

  1. consul介绍

    consul服务发现是用go语言的开源框架,是一个分布式, 高可用,数据中心感知的解决方案,用于跨任何运行时平台和公共云或私有云连接。consul是服务发现和配置工具。主要功能包括:

    (1) 服务发现 – consul使用简单的服务来注册自己,并通过dns或http接口发现其他服务。还可以注册外部服务,比如saas提供者。

    (2) 运行状况检查 -运行状况检查使consul能够快速向操作员发出有关群集中任何问题的警报, 与服务发现的集成可防止将流量路由到不健康的主机,并启用服务级别的断路器。

    (3) key/value存储 – 灵活的key/value存储可以存储动态配置,功能标记,协调,领导者选举等。简单的http api使其易于在任何地方使用。

    (4) 多数据中心 – consul可以识别数据中心,并且可以支持任意数量的区域而无需复杂的配置。

    (5) 服务分段 – consul 连接通过自动tls加密和基于身份的授权实现安全的服务到服务通信。

    使用consul示例:https://www.cnblogs.com/zhang-xiang/p/10437488.html

 

  2. eureka介绍

    eureka服务发现是用java语言的开源框架,最新版本为19.9 (有报道后面2.0版本不开源)。是一种基于rest的服务,主要用于aws云,用于定位服务,以实现中间层服务器的负载平衡和故障转移。

    使用eureka示例:service discovery demo with eureka

    示例介绍:https://www.c-sharpcorner.com/article/building-api-gateway-using-ocelot-in-asp-net-core-service-discoveryeureka/

 

二.演示项目介绍

  本篇重点了解consul的使用,下面参考开源项目github , 本篇在部署上 对比 参考示例 有些小改动,项目使用了ocelot + identityserver4 + consul中间件。

 

  说明:

  (1) 用到的软件包括:centos系统,  iis,  fiddler。其中centos系统用于做consul服务注册,iis做webapi的宿主承载,fiddler用于客户端模拟测试。

  (2) 演示中 identityserver4服务认证和apigateway网关项目由vs2017 来做宿主承载,但也可以用iis承载。

项目名称

ip和端口

说明

apigateway

http://localhost:38039

 

网关项目。统一访问入口点,在生产环境下ip要在广域网,供第三方客户端访问。

做好网关路由配置,将自动转发。

identityserver4

http://127.0.0.1:8021

is4令牌服务。ip是在局域网, 通过web api来调用令牌

service a/b

http://127.0.0.1:8010 (a)

http://127.0.0.1:8011 (b)

服务项目。ip是在局域网,由网关转发进来访问。

consul 搭建

http://172.168.18.201:8500

服务发现。在linux中启动consul服务,默认是8500端口,用于监听服务的健康状态。

在linux中需要拼通服务ip及port, 反之一样。可telnet命令。

配置服务注册文件

fiddler客户端模拟

 

调用服务a获取is4令牌,通过该令牌访问服务a受保护的接口

   

. web api服务   

  参考开源项目,service a和service b服务项目相关配置都一样,以service a为例: 

  1.项目中有三个api接口

    (1) 一个必须要诊断接口api/health 

    (1) 一个必须要的获取令牌接口api/session

    (3) 一个业务测试接口api/values。 因为业务接口是受保护的,所以该接口加了[authorize],需要令牌来访问

    [authorize]
    [route("api/[controller]")]
    [apicontroller]
    public class valuescontroller : controllerbase
    {
        // get api/values
        [httpget]
        public actionresult<ienumerable<string>> get()
        {
            return new[] { "value1", "value2" };
        }
    }

  2. 在启动时,加了授权中间件,采用jwtbearer方案。设置了受信任的is4服务基地址,以及audience保护的资源。

     services.addauthentication("bearer")
                .addjwtbearer("bearer", options =>
                {
                    options.authority = "http://127.0.0.1:8021";
                    options.requirehttpsmetadata = false;
                    options.audience = "serviceb";
                });

  

四. apigateway项目

  1. 在网关项目中,配置ocelot文件

   {
  "reroutes": [
    {
      "downstreampathtemplate": "/api/{everything}",
      "downstreamscheme": "http",
      //客户端通过/servicea来访问servicea的服务
      "upstreampathtemplate": "/servicea/{everything}",
      "upstreamhttpmethod": [ "get", "post", "delete", "put" ],
      //服务发现consul用到
      "servicename": "servicea",
      "loadbalanceroptions": {
        "type": "leastconnection"
      }
    },
    {
      "downstreampathtemplate": "/api/{everything}",
      "downstreamscheme": "http",
      "upstreampathtemplate": "/serviceb/{everything}",
      "upstreamhttpmethod": [ "get", "post", "delete", "put" ],
      "servicename": "serviceb",
      "loadbalanceroptions": {
        "type": "leastconnection"
      }
    }
  ],
  "globalconfiguration": {
    //配置consul的信息
    "servicediscoveryprovider": {
      "host": "172.168.18.201",
      "port": 8500,
      "type": "consul"
    }
  }
}

   2.启动时添加网关中间件

    public static void main(string[] args)
        {
            new webhostbuilder()
                .usekestrel()
                .usecontentroot(directory.getcurrentdirectory())
                .configureappconfiguration((hostingcontext, config) =>
                {
                    config
                        .setbasepath(hostingcontext.hostingenvironment.contentrootpath)
                        .addjsonfile("appsettings.json", true, true)
                        .addjsonfile($"appsettings.{hostingcontext.hostingenvironment.environmentname}.json", true, true)
                        .addjsonfile("ocelot.json")
                        .addenvironmentvariables();
                })
                .configureservices(services =>
                {
                    services.addocelot().addconsul();
                })
                .configurelogging((hostingcontext, logging) =>
                {
                    //add your logging
                })
                .useiisintegration()
                .configure(app =>
                {
                    app.useocelot().wait();
                })
                .build()
                .run();
        }

 

五. identityserver令牌服务

  参考开源identityserver项目代码,在令牌服务中,使用adddevelopersigningcredential来添加临时证书,在生产环境下,可以使用addsigningcredential来添加证书。客户端基于用户名和密码的方式来获取令牌granttypes.resourceownerpassword。

 

六 consul搭建

  1. consul安装

    --下载安装包
        [root@hsr opt]# wget https://releases.hashicorp.com/consul/1.4.4/consul_1.4.4_linux_amd64.zip
    --将conusl命令移到bin目录下,方便启动
        [root@hsr opt]# mv consul /usr/local/bin/
    --测试安装是否成功,ok
    [root@hsr ~]# consul
    usage: consul [--version] [--help] <command> [<args>]

  2.添加服务注册放到/usr/etc/

  3. 启动客户端agent 测试

  consul agent -dev -data-dir=/usr/etc  -config-dir=/usr/etc/consul.json -client 172.168.18.201

    启动成功后,会每隔10秒检查一次服务的健康状态,如下所示:

           -dev开发模式,启动该参数配置下,不会有任何持久化操作,即不会有任何数据写入到磁盘

           -config-file 指定服务注册文件

           -client指定当前ip,默认是127.0.0.1

           -data-dir指定agent储存状态的数据目录

  4.关闭201防火墙, 在win系统上访问服务发现管理界面如下:

    systemctl stop firewalld.service

  

七.fiddler测试

  1. 测试开始步骤:

    (1) 两个服务servera/serverb发布到iis上。

    (2) 在vs2017中启动apigateway网关项目和is4项目。

    (3) 在linux系统中启动consul(现只是监听服务是否健康)
  2.测试servera服务

    (1)通过用户名和密码,获取要访问servera服务的令牌

    (2) 获取受保护的api接口,将拿到的令牌加到headers中去请求

    (3) 请求http://localhost:38039/servicea/values数据接口成功,如下所示:

 

 

  参考文献

    

      参考项目示例