ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Ocelot学习(二)

2022-02-23 02:01:03  阅读:215  来源: 互联网

标签:ocelot Consul 配置 学习 json Ocelot true


目录

Ocelot学习(二)

入门

Ocelot 旨在与 ASP.NET 一起使用,目前在 net6.0 上。

.NET 6.0

安装 NuGet 包

使用 nuget 安装 Ocelot 及其依赖项。您将需要创建一个 net6.0 项目并将包放入其中。然后按照下面的启动和配置部分启动并运行。

Install-Package Ocelot

所有版本都可以在这里找到。

配置

下面是一个很基础的ocelot.json。它不会做任何事情,但应该让 Ocelot 开始。

{
    "Routes": [],
    "GlobalConfiguration": {
        "BaseUrl": "https://api.mybusiness.com"
    }
}

如果您想要一些实际执行某些操作的示例,请使用以下命令:

{
    "Routes": [
        {
        "DownstreamPathTemplate": "/todos/{id}",
        "DownstreamScheme": "https",
        "DownstreamHostAndPorts": [
            {
                "Host": "jsonplaceholder.typicode.com",
                "Port": 443
            }
        ],
        "UpstreamPathTemplate": "/todos/{id}",
        "UpstreamHttpMethod": [ "Get" ]
        }
    ],
    "GlobalConfiguration": {
        "BaseUrl": "https://localhost:5000"
    }
}

这里最需要注意的是BaseUrl。Ocelot 需要知道它正在运行的 URL 以便执行 Header 查找和替换以及某些管理配置。设置此 URL 时,它应该是客户端将看到 Ocelot 在其上运行的外部 URL,例如,如果您正在运行容器,Ocelot 可能会在 url http://123.12.1.1:6543上运行,但它前面有类似 nginx 的东西在https上响应://api.mybusiness.com。在这种情况下,Ocelot 基本 url 应该是https://api.mybusiness.com

如果您使用容器并且需要 Ocelot 响应http://123.12.1.1:6543上的客户端,那么您可以这样做,但是如果您要部署多个 Ocelot,您可能希望在命令行上以某种方式传递它脚本。希望您使用的任何调度程序都可以通过 IP。

程序

然后在您的 Program.cs 中,您将需要以下内容。主要需要注意的是 AddOcelot() (添加 ocelot 服务), UseOcelot().Wait() (设置所有的 Ocelot 中间件)。

using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace OcelotBasic
{
    public class Program
    {
        public static void Main(string[] args)
        {
            new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config
                    .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                    .AddJsonFile("appsettings.json", true, true)
                    .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                    .AddJsonFile("ocelot.json")
                    .AddEnvironmentVariables();
            })
            .ConfigureServices(s => {
                s.AddOcelot();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                //add your logging
            })
            .UseIISIntegration()
            .Configure(app =>
            {
                app.UseOcelot().Wait();
            })
            .Build()
            .Run();
        }
    }
}

配置

可以在此处找到示例配置。配置有两个部分。一个路由数组和一个 GlobalConfiguration。Routes 是告诉 Ocelot 如何处理上游请求的对象。全局配置有点 hacky,允许覆盖 Route 特定的设置。如果您不想管理大量 Route 特定设置,它会很有用。

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

这是一个示例路由配置,您不需要设置所有这些东西,但这是目前可用的所有内容:

{
          "DownstreamPathTemplate": "/",
          "UpstreamPathTemplate": "/",
          "UpstreamHttpMethod": [
              "Get"
          ],
          "DownstreamHttpMethod": "",
          "DownstreamHttpVersion": "",
          "AddHeadersToRequest": {},
          "AddClaimsToRequest": {},
          "RouteClaimsRequirement": {},
          "AddQueriesToRequest": {},
          "RequestIdKey": "",
          "FileCacheOptions": {
              "TtlSeconds": 0,
              "Region": ""
          },
          "RouteIsCaseSensitive": false,
          "ServiceName": "",
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
              {
                  "Host": "localhost",
                  "Port": 51876,
              }
          ],
          "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,
              "MaxConnectionsPerServer": 100
          },
          "DangerousAcceptAnyServerCertificateValidator": false
      }

合并配置文件

此功能是在Issue 296中提出的,它允许用户拥有多个配置文件,以便更轻松地管理大型配置。

您可以调用 AddOcelot(),而不是直接添加配置,例如 AddJsonFile(“ocelot.json”),如下所示。

.ConfigureAppConfiguration((hostingContext, config) =>
    {
        config
            .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
            .AddJsonFile("appsettings.json", true, true)
            .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
            .AddOcelot(hostingContext.HostingEnvironment)
            .AddEnvironmentVariables();
    })

在这种情况下,Ocelot 将查找与 (?i)ocelot.([a-zA-Z0-9]*).json 模式匹配的任何文件,然后将它们合并在一起。如果要设置 GlobalConfiguration 属性,则必须有一个名为 ocelot.global.json 的文件。

Ocelot 合并文件的方式基本上是加载它们,循环它们,添加任何路由,添加任何 AggregateRoutes,如果文件名为 ocelot.global.json,则添加 GlobalConfiguration 以及任何路由或 AggregateRoutes。然后,Ocelot 会将合并后的配置保存到一个名为 ocelot.json 的文件中,这将在 ocelot 运行时用作事实来源。

目前在此阶段没有验证,它仅在 Ocelot 验证最终合并配置时发生。这是您在调查问题时需要注意的事项。如果您有任何问题,我建议您始终检查 ocelot.json 中的内容。

您还可以为 Ocelot 指定一个特定路径来查找配置文件,如下所示。

.ConfigureAppConfiguration((hostingContext, config) =>
    {
        config
            .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
            .AddJsonFile("appsettings.json", true, true)
            .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
            .AddOcelot("/foo/bar", hostingContext.HostingEnvironment)
            .AddEnvironmentVariables();
    })

Ocelot 需要 HostingEnvironment,因此它知道从算法中排除任何特定环境。

在 consul 中存储配置

您需要做的第一件事是在 Ocelot 中安装提供 Consul 支持的 NuGet 包。

Install-Package Ocelot.Provider.Consul

然后在注册服务时添加以下内容,Ocelot 将尝试在 consul KV 存储中存储和检索其配置。

services
   .AddOcelot()
   .AddConsul()
   .AddConfigStoredInConsul();

您还需要将以下内容添加到您的 ocelot.json。这就是 Ocelot 找到您的 Consul 代理并进行交互以从 Consul 加载和存储配置的方式。

"GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
        "Host": "localhost",
        "Port": 9500
    }
}

在研究了 Raft 共识算法并发现它的超级难之后,我决定创建这个功能。为什么不利用 Consul 已经给你这个的事实呢!我想这意味着如果你想充分利用 Ocelot,你现在就把 Consul 作为一个依赖项。

在向本地领事代理发出新请求之前,此功能有 3 秒的 ttl 缓存。

更改时重新加载 JSON 配置

Ocelot 支持在更改时重新加载 json 配置文件。例如,以下将在手动更新 ocelot.json 文件时重新创建 Ocelots 内部配置。

config.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);

配置密钥

如果您使用 Consul 进行配置(或将来使用其他提供程序),您可能需要键入您的配置,以便您可以拥有多个配置

标签:ocelot,Consul,配置,学习,json,Ocelot,true
来源: https://www.cnblogs.com/AJun816/p/15925681.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有