# Ocelot Demo

for .net core 3.1 (用时约20分钟)

具体操作

步骤:

  • 创建天气预报模板项目WeatherForecast(预备)
  • 创建空项目
  • 修改配置add logging
  • add ocelot nuget package
  • 运行ocelotdemo应用程序(Routing)
  • 添加jwtbearer引用并配置后运行(Ahthentication)
  • 限流控制(Rate limiting)
  • 缓存控制策略(Response Caching)
  • 混合策略

创建天气预报模板项目(预备)

本项目服务供ocelot调用。

在ocelotdemo项目解决方案下添加新项目。

image-20210223141323906

选择现有的API模板

image-20210223141513861

编译,运行.\WeatherForecast\bin\Debug\netcoreapp3.1下面的WeatherForecast.exe启动Web应用服务。

image-20210223142718444

创建空项目

新建

image-20210223102929041

选择 ASP.NET Core Web 应用程序

image-20210223103156798

输入名称OcelotDemo,打勾

image-20210223103358818

ASP.NET Core 3.1 空项目

image-20210223103652222

创建,完成。

image-20210223103928776

修改配置(Add logging)

Program.cs配置logging

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
            .ConfigureLogging(logging => logging.AddConsole());

添加Ocelot nuget 包

项目右键--管理Nuget程序包,浏览,输入ocelot,选择版本16.0.1 ,这个版本支持.net core v3.1

image-20210223105446844

安装,确定

image-20210223105601010

接受许可

image-20210223105641319

安装完成后,修改Startup.cs

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

public class Startup
{
    // ...
    public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot();
        }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //...
            app.UseOcelot().Wait();
        }
}

添加新建item--JSON文件,命名ocelot.json

image-20210223110446379

复制一个副本改名为ocelot.dev.json

image-20210223110705002

项目右键,属性,调试,修改变量值为dev

image-20210223111517677

保存。

修改launchSettings.json文件

"applicationUrl": "https://localhost:5021;http://localhost:5020"

配置ocelot.dev.json

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/weatherforecast",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": "5001"
        }
      ],
      "UpstreamPathTemplate" : "/api/weather",
      "UpstreamHttpMethod" : [ "Get" ]
    }
  ],
  "GlobalConfiguaration": {
    "BaseUrl": "https://localhost:5021"
  }
}

修改模拟器

image-20210223120207342

修改Program.cs

public static class Program

加入配置文件

 public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                    webBuilder.UseStartup<Startup>();
                    webBuilder.ConfigureAppConfiguration(config =>
                    config.AddJsonFile($"ocelot.{env}.json"));
                })
            .ConfigureLogging(logging => logging.AddConsole());

运行应用程序

image-20210223124515140

输入url:https://localhost:5021/api/weather

image-20210223143329808

可以看到调用了https://localhost:5001/weatherforecast

image-20210223143414671

添加jwtbearer引用并配置后运行

这个可以看另外专题

添加引用

项目右键--管理Nuget程序包,浏览,输入jwtbearer,选择Microsoft.AspNetCore.Authentication.JwtBearer,版本3.1.12,可以看到该版本支持.net core v3.1

image-20210223144546757

预览更改,确定

image-20210223144616150

接受许可证,完成

配置

修改Startup.cs文件

// 引用
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

// ConfigureServices方法
var secret = "Thisismytestprivatekey";
            var key = Encoding.ASCII.GetBytes(secret);
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            services.AddOcelot();

// Configure方法
app.UseRouting();
//后面加
app.UseAuthentication();
// ...

修改ocelot.dev.json文件,

Routes添加AuthenticationOptions选项:

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/weatherforecast",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": "5001"
        }
      ],
      "UpstreamPathTemplate" : "/api/weather",
      "UpstreamHttpMethod": [ "Get" ],
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "Bearer",
        "AllowedScopes": []
      }
    }
  ],
  "GlobalConfiguaration": {
    "BaseUrl": "https://localhost:5021"
  }
}

再运行

可以在浏览器F12打开Debug看到401错误

image-20210223151425900

查看控制台窗口,可以看到unauthenticated errors字样

image-20210223151654317

限流控制

修改配置ocelot.dev.json文件,在Routes中添加RateLimitOptions选项。完成后配置:

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/weatherforecast",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": "5001"
        }
      ],
      "UpstreamPathTemplate": "/api/weather",
      "UpstreamHttpMethod": [ "Get" ],
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "Bearer",
        "AllowedScopes": []
      },
      "RateLimitOptions": {
        "ClientWhitelist": [],
        "EnableRateLimiting": true,
        "Period": "5s",
        "PeriodTimespan": 1,
        "Limit": 1
      }
    }
  ],
  "GlobalConfiguaration": {
    "BaseUrl": "https://localhost:5021"
  }
}

再次运行,使用Postman测试5秒内频繁请求多次,将被截流。

缓存控制策略

项目右键--管理Nuget程序包,浏览,输入ocelot,选择Ocelot.Cache.CacheManager,版本16.0.1

image-20210223153638137

确定,我接受

image-20210223153840752

完成后修改Startup.cs配置参数。

using Ocelot.Cache.CacheManager;

// 在`ConfigureServices`方法中,
services.AddOcelot().AddCacheManager(settings => settings.WithDictionaryHandle());

修改配置ocelot.dev.json文件,在Routes中添加FileCacheOptions选项。完成后配置(设置30秒):

"FileCacheOptions": { "TtlSeconds": 30 }

再运行,可以看到30秒内只请求了一次api(200 \),超过30秒后再请求才会再次发起api请求。

image-20210223155817803

混合策略

结合缓存和限流,修改配置如下:

image-20210223160636722

试运行效果

image-20210223160544397

可以看到缓存效果(5秒内)及限流控制(15秒内只能请求1次)。

image-20210223161101953

注意到,PeriodTimespan在1秒后恢复了,所以实际效果是当发起一次请求后开始计时,但在1秒后又重置了(熔断恢复时间),故只有1秒内请求超过一次才会熔断。

(END)

Copyright © 德和居 2021 粤ICP备20069867号 在CC-BY-NC-SA 4.0协议下授权使用,除非另有说明 all right reserved,powered by Gitbook本文修订时间: 2021-02-23 22:23:58

results matching ""

    No results matching ""

    results matching ""

      No results matching ""