Net Core 网关 Ocelot 简单案例

1、什么是Ocelot

  Ocelot是一个用.NET Core实现并且开源的API网关,它功能强大,包括了:路由、请求聚合、服务发现、认证、鉴权、限流熔断、并内置了负载均衡器与Service Fabric、Butterfly Tracing集成。

2、前期准备工作

  新建一个Web API,返回IP+Port字符串(有利于我们直观感受)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace StudyGateway.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private IConfiguration _configuration;
        public WeatherForecastController(IConfiguration configuration)
        {
            this._configuration = configuration;
        }

        [HttpGet]
        public string Get()
        {
            string ip = _configuration["IP"];
            string port = _configuration["Port"];
            return $@"{ip} {port}";
        }
    }
}

  CMD启动该站点

dotnet StudyGateway.dll --urls="http://*:5177" --ip="127.0.0.1" --port=5177

  显示截图:

  

 

 

 3、开始设计网关(Gateway)
  创建一个新的Net Core Api项目,引用Ocelot包(注意版本对应 core 3.x 对应 Ocelot 15)

  安装完成后,修改Startup,因为这个站点只是作为网关,所以只需要以下配置

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace MyOcelot
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot(new ConfigurationBuilder().AddJsonFile("configuration.json").Build());
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseOcelot();
        }
    }
}

  新增一个configuration.json,作为Ocelot的配置文件(记得修改 [复制到输出目录])

  配置下游站点

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "127.0.0.1",
          "Port": 5177
        }
      ],
      "UpstreamPathTemplate": "/GateWay/{url}", //这个url会转到上面的url
      "UpstreamHttpMethod": [ "Get", "POST" ]
    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/administration"
  }
}  

  启动项目,访问

  

 

  成功转载!!!

4、负载均衡策略

  前期准备工作的网站,通过CMD再启动一个新实例

dotnet StudyGateway.dll --urls="http://*:5178" --ip="127.0.0.1" --port=5178

  修改Ocelot配置文件,新增一个下游站点

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "127.0.0.1",
          "Port": 5177
        },
        {
          "Host": "127.0.0.1",
          "Port": 5178
        }
      ],
      "UpstreamPathTemplate": "/GateWay/{url}", //这个url会转到上面的url
      "UpstreamHttpMethod": [ "Get", "POST" ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //负载均衡类型:轮询(其他类型也有,不一一列举了)
      }
    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/administration"
  }
}  

  重新生成,访问:

  

  

 5、缓存策略

  安装Nuget包:Ocelot.Cache.CacheManager

  修改Ocelot配置文件,添加FileCacheOptions节点

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "127.0.0.1",
          "Port": 5177
        },
        {
          "Host": "127.0.0.1",
          "Port": 5178
        }
      ],
      "UpstreamPathTemplate": "/GateWay/{url}", //这个url会转到上面的url
      "UpstreamHttpMethod": [ "Get", "POST" ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //负载均衡类型:轮询(其他类型也有,不一一列举了)
      },
      "FileCacheOptions": {
        "TtlSeconds": 3,
        "Region": "somename"
      }
    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/administration"
  }
}  

  刷新

http://localhost:57789/GateWay/weatherforecast

  访问后会缓存地址3秒。

  比如:第一次访问,转载到Port=5177,3秒内都会访问5177

 

 

 

 

  

 

posted @ 2022-10-15 15:44  wskxy  阅读(321)  评论(0编辑  收藏  举报