您的位置:首页 > 其它

Ocelot简易教程(二)之快速开始

2018-08-30 22:45 701 查看
Ocelot是为.net core量身定做的,目前是基于 netstandard2.0进行构建的。

.NET Core 2.1中如何使用呢?

安装NuGet package

使用nuget安装Ocelot及其依赖项。您需要创建一个netstandard2.0项目并将其Package安装到项目中。然后按照下面的“启动”和“ 配置”节点启动并运行。

安装命令
Install-Package Ocelot


你可以通过下面的链接查看Ocelot的历史版本https://www.nuget.org/packages/Ocelot/ 目前最新版是10.0.4。最新版最近正在进行重构,更新比较频繁。

配置

以下配置是一个非常基础的Ocelot.json配置,他不会做任何事情,但却可以让ocelot正常运行。

{
"ReRoutes": [],
"GlobalConfiguration": {
"BaseUrl": "https://api.yilezhu.cn"
}
}

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

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


特别需要注意的是,这里的Ocelot.json配置文件需要在VS中右键修改为“始终复制”属性。


Program配置方法

官方文档是按照下面进行配置的。不过个人还是习惯在Sartup.cs文件中进行相关的配置。博主就先贴出官方文档给出的配置方法。

然后在你的Program.cs你将按照如何代码进行配置。这里最主要的是AddOcelot() 添加 ocelot 服务), UseOcelot().Wait() (使用 Ocelot中间件).

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();
}

Startup配置方法

我个人也比较习惯在Startup.cs中进行配置,不习惯在Program.cs中配置。下面是我配置的一种方式,当然你也可以自由发挥。

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();

services.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("ocelot.json")
.Build());
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

await app.UseOcelot();

app.UseMvc();
}

总结

今天只是给大家介绍Ocelot的非常非常简单地使用,可以说零配置,并介绍了官方的使用方法以及我平时的使用方式,只为了快速开始Ocelot,让项目能够跑起来。接下来我们会详细的介绍Ocelot的配置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: