侧边栏

Ocelot中文文档-入门(转)

原文地址:https://www.cnblogs.com/snaildev/articles/9151466.html

Ocelot只能用于.NET Core,目前是为netcoreapp6.0构建的,这个文档可能会帮你了解Ocelot是否适合你。

.NET 6.0

安装NuGet包

使用nuget安装Ocelot和它的依赖。你需要创建一个netcoreapp2.0的项目并安装Ocelot包。然后按照下面的配置部分启动并运行。

Install-Package Ocelot

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

配置

下面是个很简单的ocelot.json。它不做任何事情,但是可以上Ocelot启动了。

1
2
3
4
5
6
{
    "ReRoutes": [],
    "GlobalConfiguration": {
        "BaseUrl""https://api.mybusiness.com"
    }
}

这里最重要的就是BaseUrl了。Ocelot需要知道它正在运行的URL,以便头部查找和替换以及一些管理配置。设置此URL时,它应该是客户端将看到的Ocelot运行的外部URL。例如,假如你在容器中运行Ocelot的url是http://123.12.1.1:6543,但是在它前面有像nginx一样的代理在响应https://api.mybusiness.com。在这种情况下Ocelot的BaseUrl应该是https://api.mybusiness.com

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

程序

然后在你的Program.cs中,你会想要以下内容。主要就是AddOcelot()(添加ocelot服务),UseOcelot().Wait()(设置所有的Ocelot中间件)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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"truetrue)
                    .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json"truetrue)
                    .AddJsonFile("ocelot.json")
                    .AddEnvironmentVariables();
            })
            .ConfigureServices(s => {
                s.AddOcelot();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                //add your logging
            })
            .UseIISIntegration()
            .Configure(app =>
            {
                app.UseOcelot().Wait();
            })
            .Build()
            .Run();
    }
}

.NET Core 

原文

如需转载,请在显眼处标明本文链接,谢谢。
posted @ 2022-09-30 15:09  我有我的骄傲  阅读(171)  评论(0)    收藏  举报