Ocelot 网关搭建

Ocelot 网关搭建

官网:http://threemammals.com/ocelot

文档:https://ocelot.readthedocs.io/en/latest/

Github:https://github.com/ThreeMammals/Ocelot

Ocelot是一个基于 .net core的开源WebAPI服务网关项目

它包括了路由、请求聚合、服务发现、认证鉴权、限流、负载均衡等功能。

这些功能都可以直接通过修改json配置文件即可使用,非常方便。Ocelot是系统中对外暴露的一个请求入口,所有外部接口都必须通过这个网关才能向下游API发出请求。

一. 搭建 Ocelot 项目

 创建 NetCore WebApi项目,框架net 5.0 , 安装 Ocelot  nuget包

在项目的根目录添加一个.json配置文件,文件名自定义,此案例为Ocelot.json.添加配置如下:

{    
    "ReRoutes": [],    
    "GlobalConfiguration": {}
}

ReRoutes是一个数组,将会包含服务器的路由配置

GlobalConfiguration则是一个全局配置项。 


修改Program.cs文件,将该配置文件添加到 .net core configuration中
因为 .net core支持当配置文件被修改后会重新加载,所以如果我们需要支持重新加载,可修改为:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, builder) => { builder.AddJsonFile("Ocelot.json", optional: false, reloadOnChange: true); })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

将Ocelot作为中间件注册,修改 Startup.cs 

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddOcelot(); 
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "OcelotWebHost v1"));
            }
            app.UseOcelot().Wait();
     }

Ocelot 网关搭建完成!

Ocelot.json 配置参数介绍

配置文件中包含两个配置项:Routes和GlobalConfiguration。
GlobalConfiguration : 它是一个全局配置项,通常我们都要在这个配置项中添加一个属性BaseUrl,BaseUrl就是Ocelot服务对外暴露的Url。

暂时设置成与项目端口一致,

"GlobalConfiguration": {"BaseUrl": "https://localhost:5001"}

 Routes是一个数组,其中的每一个元素代表了一个路由,而一个路由所包含的所有可配置参数如下:

{    
    "DownstreamPathTemplate": "/",    
    "UpstreamPathTemplate": "/",    
    "UpstreamHttpMethod": 
    [        
        "Get"
    ],    
    "AddHeadersToRequest": {},    
    "AddClaimsToRequest": {},    
    "RouteClaimsRequirement": {},    
    "AddQueriesToRequest": {},    
    "RequestIdKey": "",    
    "FileCacheOptions": 
    {        
        "TtlSeconds": 0,        
        "Region": ""
    },    
    "ReRouteIsCaseSensitive": false,    
    "ServiceName": "",    
    "DownstreamScheme": "http",    
    "DownstreamHostAndPorts": 
    [
        {            
        "Host": "localhost",            
        "Port": 8001,
        }
    ],    
    "QoSOptions": 
    {        
        "ExceptionsAllowedBeforeBreaking": 0,        
        "DurationOfBreak": 0,        
        "TimeoutValue": 0
    },    
    "LoadBalancer": "",    
    "RateLimitOptions": 
    {        
        "ClientWhitelist": [],        
        "EnableRateLimiting": false,        
        "Period": "",        
        "PeriodTimespan": 0,        
        "Limit": 0
    },    
    "AuthenticationOptions": 
    {        
        "AuthenticationProviderKey": "",        
        "AllowedScopes": []
    },    
    "HttpHandlerOptions": 
    {        
        "AllowAutoRedirect": true,        
        "UseCookieContainer": true,        
        "UseTracing": true
    },    
    "UseServiceDiscovery": false
}

 注:

Downstream 下游服务配置

UpStream 上游服务配置

Aggregates 服务聚合配置

ServiceName, LoadBalancer, UseServiceDiscovery 服务发现配置

AuthenticationOptions 服务认证配置

RouteClaimsRequirement Claims 鉴权配置

RateLimitOptions 限流配置

FileCacheOptions 缓存配置

QosOptions 服务质量与熔断配置

DownstreamHeaderTransform 头信息转发配置

二. 测试样例

1) 增加 net5 框架的 webapi 项目:OService1 

修改 launchSettings.json 端口 

      "applicationUrl": "https://localhost:6001;http://localhost:7001",

 增加 webapi 控制器:CatsController.cs

namespace OService1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CatController : ControllerBase
    {
        [Route("GetList")]
        [HttpGet]
        public string GetList()
        {
            return $"get list success! This is from {HttpContext.Request.Host.Value}, path: {HttpContext.Request.Path}";
        }
    }
}

2) 增加 net5 框架的 webapi 项目:OService2

修改 launchSettings.json 端口 

"applicationUrl": "https://localhost:6002;http://localhost:7002",

  增加 webapi 控制器:AirController.cs 

namespace OService2.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AirController : ControllerBase
    {
        [Route("GetArr/{index}")]
        [HttpGet]
        public string GetArr(int index)
        {
            return $"get arr success! index :{index}, This is from {HttpContext.Request.Host.Value}, path: {HttpContext.Request.Path}";
        } 
    }
}

 3) 修改OcelotWebHost 项目中的 Ocelot.json 配置文件

{
  "Routes": [
    //路由一
    {
      "DownstreamPathTemplate": "/api/cat/getlist", //下游路径
      "DownstreamScheme": "https",  //http,https
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",  //下游地址
          "Port": 6001  //下游端口
        }
      ],
      "UpstreamPathTemplate": "/ocelot/getlist",//上游路径
      "UpstreamHttpMethod": [ "Get" ]
    },
    //路由二
    {
      "DownstreamPathTemplate": "/api/air/getarr/{index}",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 6002
        }
      ],
      "UpstreamPathTemplate": "/ocelot/getarr/{index}",
      "UpstreamHttpMethod": [ "Get" ]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:5001"
  }
}

 测试1:

访问地址:https://localhost:5001/ocelot/getlist

转发地址:https://localhost:6001/api/cat/getlist

 测试2:

访问地址:https://localhost:5001/ocelot/getarr/4

转发地址:https://localhost:6002/api/air/getarr/4

参考:http://letyouknow.net/ocelot/ocelot-tutorial-1.html

项目:https://gitee.com/wuxincaicai/ocelothost.git

原文地址:https://www.cnblogs.com/1285026182YUAN/p/15234331.html