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在
上響應用戶端的請求, 那麼你可以這樣做但是如果要部署多個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的配置。