当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core系列 59 Ocelot 构建基础项目示例

asp.net core系列 59 Ocelot 构建基础项目示例

2019年04月24日  | 移动技术网IT编程  | 我要评论

nhdt-153,夏正兰,电子游艺89168官方赌博公司

一.入门概述

  从这篇开始探讨ocelot,ocelot是一个.net api网关,仅适用于.net core,用于.net面向微服务/服务的架构中。当客户端(web站点、ios、 app 等)访问web api时,需要先统一入口点进入ocelot网关(ocelot可以做很多事情例如路由,身份验证,服务发现,日志记录等,下面列出了功能基本),再由ocelot分发到web api。ocelot官方希望is4一起使用,实现令牌轻松集成。

  ocelot是一组按特定顺序排列的中间件,查看源码会发现ocelot是一堆的middleware组成的一个管道。

  ocelot操控httprequest对象到其配置指定的状态,在中间件中ocelot创建一个httprequestmessage对象,该对象用于向下游服务(wep api)发出请求。发出请求的中间件是ocelot管道中的最后一件事。它不会调用下一个中间件。

  当下游服务response返回ocelot管道时,将检索下游服务的响应。有一个中间件将httpresponsemessage映射到httpresponse对象并返回给客户端。

 

  通过官方部署架构图介绍,可以了解到:ocelot有5种部署方式包括:

         (1) ocelot基本实现

         (2) ocelot结合is4、

         (3) ocelot多个实现(高可用,负载)

         (4) ocelot结合consul(健康检查,服务注册)、

         (5) ocelot结合service fabric。

  查看,在架构图中,ocelot网关暴露在广域网的一个访问入口,供客户端调用。而web api是在局域网中,由ocelot来转发。

 

  ocelot的功能基本包括:

                   路由

                   请求聚合

                   consul和eureka的服务发现

                   service fabric

                   websockets

                   authentication认证

                   authorisation授权

                   限速

                   高速缓存

                   重试策略/ qos

                   负载均衡

                   日志/跟踪/关联

                   标头/查询字符串/声明转换

                   自定义中间件/委托处理程序

                   配置/管理rest api

                   platform / cloud agnostic

 

         安装nuget包

                  install-package ocelot

 

二.ocelot 基础项目演示

  下面通过贡献者的开源项目来学习ocelot,掌握一个基础项目应用,学习起来也更直观。示例有三个项目:一个是网关apigateway项目,有二个是web api服务。 项目实现的功能是:客户端统一通过网关作为入口点访问,实现路由的功能。github开源地址   架构如下图所示:

  

  2.1 customersapiservices项目

    该项目是一个web api项目,用来处理客户事务的api服务。该地址为http://localhost:9001, 可以在“项目选项”中指定url,也可以在host启动时配置。

    (1) program类添加useurls

        public static iwebhostbuilder createwebhostbuilder(string[] args) =>
            webhost.createdefaultbuilder(args)
                   .usestartup<startup>().useurls("http://*:9001"); 

    (2)custimersapiservices项目中创建一个customerscontroller 

   [route("api/[controller]")]
    public class customerscontroller : controller
    {        
        [httpget]
        public ienumerable<string> get()
        {
            return new string[] { "catcher wong", "james li" };
        }

        [httpget("{id}")]
        public string get(int id)
        {
            return $"catcher wong - {id}";
        }            
    }

 

   2.2 productsapiservices项目 

    该项目是一个web api项目,处理产品某事的api服务。该地址为http://localhost:9002, 可以在“项目选项”中指定url,也可以在host启动时配置。

    (1) program类添加useurls

        public static iwebhostbuilder createwebhostbuilder(string[] args) =>
            webhost.createdefaultbuilder(args)
                   .usestartup<startup>().useurls("http://*:9002");   

    (2) 在productsapiservices项目中创建productscontroller

    [route("api/[controller]")]
    public class productscontroller : controller
    {
        
        [httpget]
        public ienumerable<string> get()
        {
            return new string[] { "surface book 2", "mac book pro" };
        }
    }

 

  2.3 apigateway项目

    该项目是ocelot网关项目,先安装ocelot包。在项目中添加一个ocelot的json配置文件,这里创建的是configuration.json文件。

    (1) configuration.json(配置ocelot)

    {
  //reroutes:处理上游请求的对象(客户端),每个数组{} 就是配置:上游地址和对应下游地址
  "reroutes": [
    {
      //以downstream开头的,是要转发到下游服务器的地址(customersapiservices),与nginx转发类似
      //下面所有downstream开头的,组成一个转发url,转发地址是http://localhost:9001/api/customers
      "downstreampathtemplate": "/api/customers",
      "downstreamscheme": "http",
      // "downstreamhost": "localhost",
      // "downstreamport": 9001,
      //转发到下游服务器的主机和端口。
      "downstreamhostandports": [
        {
          "host": "localhost",
          "port": 9001
        }
      ],
      //upstream开头是指上游服务器(客户端)访问地址,通过http get方式访问。
      //也就是说客户端访问http://localhost:9000/customers 实际是转发到了http://localhost:9001/api/customers的服务
      "upstreampathtemplate": "/customers",
      "upstreamhttpmethod": [ "get" ]
    },
    {
      "downstreampathtemplate": "/api/customers/{id}",
      "downstreamscheme": "http",
      // "downstreamhost": "localhost",
      // "downstreamport": 9001,
      "downstreamhostandports": [
        {
          "host": "localhost",
          "port": 9001
        }
      ],
      "upstreampathtemplate": "/customers/{id}",
      "upstreamhttpmethod": [ "get" ]
    },
    {
      "downstreampathtemplate": "/api/products",
      "downstreamscheme": "http",
      // "downstreamport": 9002,
      // "downstreamhost": "localhost",
      "downstreamhostandports": [
        {
          "host": "localhost",
          "port": 9002
        }
      ],
      "upstreampathtemplate": "/api/products",
      "upstreamhttpmethod": [ "get" ]
    }
  ],
  //全局配置,允许覆盖reroutes特定设置
  "globalconfiguration": {
    "requestidkey": "ocrequestid",
    "administrationpath": "/administration"
  }
}

    (2) startup类,使用ocelot

          public static iwebhostbuilder createwebhostbuilder(string[] args) =>
            webhost.createdefaultbuilder(args)
                   //.usestartup<startup>()
                //设置网关url
                   .useurls("http://*:9000")
                   .configureappconfiguration((hostingcontext, config) =>
               {
                   config
                       .setbasepath(hostingcontext.hostingenvironment.contentrootpath)
                    //添加ocelot配置文件
                       .addjsonfile("configuration.json")
                       .addenvironmentvariables();
               })
               .configureservices(s =>
               {
                //添加服务
                   s.addocelot();
                   s.addmvc().setcompatibilityversion(compatibilityversion.version_2_1);
               })
                .configure(a =>
                {        
                //添加中间件            
                    a.useocelot().wait();
                });

    

  最后开始测试:

    (1) 启动customersapiservices web api服务程序 http://www.lhsxpumps.com/_localhost:9001

    (2) 启动productsapiservices web api服务程序  http://localhost:9002

    (3) 启动 apigateway 网关服务程序  http://localhost:9000

    

 

三. 关于reroutes路由介绍

  在上面示例中,使用了基本的路由配置,在ocelot路由配置中,还有许多特性,比如:   

  (1) 给downstreampathtemplate和upstreampathtemplate设置占位符,来捕捉所有类型的reroute,是使用直接代理。

  (2) 设置上游(客户端)的主机头来匹配 "upstreamhost": "somedomain.com"。

  (3) 设置路由的优先级,priority的数字越高代表级别越高。

  (4) 设置动态路由,不必提供reroute配置。

  (5) 设置查询字符串,根据url的参数unitid={unitid}来匹配转发。

  

 

参考文献

  构建基础ocelot项目介绍

   

  

  

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网