初探.Net Core API 网关Ocelot(一)

一、介绍

Ocelot 是基于.NetCore实现的开源的API网关,支持IdentityServer认证。Ocelot具有路由、请求聚合、服务发现、认证、鉴权、限流熔断等功能,并内置了负载均衡器与Service Fabric、Butterfly Tracing集成。

Ocelot本质是由一系列特定顺序的.Net Core Middleware组成的一个管道。Ocelot接收到请求之后,用request bulider来创建一个HttpRequestMessage对象,该对象根据配置将请求下发给下游指定的服务器进行请求处理。下游服务返回response之后,一个middleware将它返回的HttpResponseMessage映射到HttpResponse,再转发给客户端。

二、如何搭建一个Ocelot项目

新建一个.net core 项目。我的环境是:vs2017,.net core 2.1,Ocelot 8.0。

NuGet安装Ocelot
image.png

添加完项目之后添加ocelot.json配置文件

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/values", // 下游游请求模板
      "DownstreamScheme": "http", //下游服务 schema
      "UpstreamPathTemplate": "/api/values", // 上游请求模板
      "UpstreamHttpMethod": [ "Get" ], // 上游请求http方法
      //下游服务的地址,如果使用LoadBalancer的话这里可以填多项
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8802
        }
      ],
      //LeastConnection – 将请求发往最空闲的那个服务器
      //"RoundRobin""轮流发送"
      //"NoLoadBalance" "总是发往第一个请求或者是服务发现",
      "LoadBalancer": "LeastConnection",
      //熔断配置
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3, //允许的异常请求数
        "DurationOfBreak": 10, //熔断的时间,单位为秒
        "TimeoutValue": 5000 //如果下游请求的处理时间超过多少则将请求设置为超时
      },
      //缓存配置
      "FileCacheOptions": {
        "TtlSeconds": 10,
        "Region": "somename" //是对缓存进行的一个分区
      },
      "HttpHandlerOptions": {
        "AllowAutoRedirect": false,
        "UseCookieContainer": false
      },
      //配置服务认证
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "",
        "AllowedScopes": []
      }
    },
    {
      "DownstreamPathTemplate": "/api/product",
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/api/product",
      "UpstreamHttpMethod": [ "Get" ],
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8801
        }
      ],
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3,
        "DurationOfBreak": 10,
        "TimeoutValue": 5000
      },
      "AuthenticationOptions": {

      }
    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/admin"
  }
}

将配置文件加入Configuration

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                 .ConfigureAppConfiguration((hostcontext, bulid) => {
                     bulid.SetBasePath(hostcontext.HostingEnvironment.ContentRootPath)
                     .AddJsonFile("ocelot.json");
                 })
                 .UseKestrel()
                .UseIISIntegration()
                .UseStartup<Startup>();
    }

添加依赖注入

       public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot();
        }

添加Ocelot中间件

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseOcelot().Wait();
    }

添加两个下游api服务,对应ocelot.json配置的下游服务

image.png

设置APIProductService端口为8801APIUserServiec端口为8802APIGateway端口为5000,设置方式如图所示:
image.png

启动项目设置为启动多个项目
image.png

启动项目

请求结果如下
image.png
image.png
image.png
image.png

http://localhost:5000/api/values请求转发给了下游服务APIUserServiec处理

image.png

将请求 http://localhost:5000/api/product 转发给了APIProductService服务进行处理

三、参考

[1] .NET Core开源API网关 – Ocelot中文文档

[2] Ocelot GitHub

猜你喜欢

转载自www.cnblogs.com/echogreat/p/9343081.html