美文网首页
asp.net core系列 59 Ocelot 构建基础项目示

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

作者: 懒懒的程序员一枚 | 来源:发表于2019-07-10 22:12 被阅读0次

    一.入门概述

    从这篇开始探讨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

    二.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://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项目介绍

    官方文档

    相关文章

      网友评论

          本文标题:asp.net core系列 59 Ocelot 构建基础项目示

          本文链接:https://www.haomeiwen.com/subject/pmakkctx.html