爲什麼這篇的標題叫“Ocelot簡易教程(二)之快速開始2”呢,因爲很多朋友跟我說上一篇“ Ocelot簡易教程(二)之快速開始1”內容太少了,只是簡單介紹Ocelot的一些簡單配置,讓Ocelot能跑起來!所以纔有了這篇快速開始2.在這篇文章中,我會一步一步記錄怎麼跑起來一個Ocelot項目,並簡單的介紹一下Ocelot怎麼實現接口間的負載均衡!此篇文章的代碼我會放在我的github上面。後續深入的記錄Ocelot的使用的時候也會沿用這次的代碼。
Ocelot簡易教程目錄
- Ocelot簡易教程(一)之Ocelot是什麼
- Ocelot簡易教程(二)之快速開始1
- Ocelot簡易教程(二)之快速開始2
- Ocelot簡易教程(三)之主要特性及路由詳解
- Ocelot簡易教程(四)之請求聚合以及服務發現
- Ocelot簡易教程(五)之集成IdentityServer認證以及授權
- Ocelot簡易教程(六)之重寫配置文件存儲方式並優化響應數據
- Ocelot簡易教程(七)之配置文件數據庫存儲插件源碼解析
一步一步開始
演示項目概述
這次的演示項目因爲要實現Ocelot的負載均衡的功能,因此至少需要三個項目:Ocelot網關,OrderApi,GoodApi .名字隨便取的,可能博主認爲這樣起名字比較順口,沒有其他特別的含義。
新建上面的三個asp.net core web api項目
相信看這篇文章的朋友至少應該懂asp.net core了吧,不然你也接觸不到Ocelot的。所以,這裏假設大家都會創建asp.net core web api(因爲真的沒什麼技術含量)。創建後的項目接口如下圖所示:
給OcelotDemo網關項目添加Ocelot包以及配置文件
首先給OcelotDemo添加Nuget包,可以右鍵“管理Nuget”包,然後搜索Ocelot添加,如下圖所示:
也可以通過命令 Install-Package Ocelot
進行安裝。方式隨你喜歡。
然後給OcelotDemo項目新建一個json文件,新建的方式就是,右鍵OcelotDemo項目,然後選擇“添加”-》“新建項”,在彈出的窗口裏面找到json文件,並寫好文件的名字即可,(當然,也可以用快捷鍵 Ctrl+Shilt+A
)如下圖所示:
當然,你還需要右鍵你剛剛設置的ocelot.json文件,並設置“複製到輸出目錄”的屬性爲“始終複製”如下所示:
接下來,可以按照我寫的非常簡單的配置進行配置。
<span style="color:#333333"><code>{
<span style="color:red">"ReRoutes"</span>: [
{
<span style="color:red">"DownstreamPathTemplate"</span>: <span style="color:#a31515">"/api/{everything}"</span>,
<span style="color:red">"DownstreamScheme"</span>: <span style="color:#a31515">"http"</span>,
<span style="color:red">"DownstreamHostAndPorts"</span>: [
{
<span style="color:red">"Host"</span>: <span style="color:#a31515">"localhost"</span>,
<span style="color:red">"Port"</span>: <span style="color:#000000">1001</span>
},
{
<span style="color:red">"Host"</span>: <span style="color:#a31515">"localhost"</span>,
<span style="color:red">"Port"</span>: <span style="color:#000000">1002</span>
}
],
<span style="color:red">"UpstreamPathTemplate"</span>: <span style="color:#a31515">"/{everything}"</span>,
<span style="color:red">"UpstreamHttpMethod"</span>: [ <span style="color:#a31515">"Get"</span>, <span style="color:#a31515">"Post"</span> ],
<span style="color:red">"LoadBalancerOptions"</span>: {
<span style="color:red">"Type"</span>: <span style="color:#a31515">"RoundRobin"</span>
}
}
],
<span style="color:red">"GlobalConfiguration"</span>: {
}
}
</code></span>
上面配置,有兩個節點,分別是ReRoutes數組,以及GlobalConfiguration。這裏簡單做一下闡述:
ReRoutes:告訴Ocelot如何處理上游的請求。
DownstreamPathTemplate:下游的路由模板,即真實處理請求的路徑模板
DownstreamScheme:請求的方式,如:http,htttps
DownstreamHostAndPorts:下游的IP以及端口,可以有多個(如果使用負載均衡),方便實現負載均衡,當然你也可以使用服務發現,實現下游服務的自動註冊與發現,這篇文章不會講解。
UpstreamPathTemplate:上游請求的模板,即用戶真實請求的鏈接
UpstreamHttpMethod:上游請求的http方法,是個數組,你可以寫多個。
LoadBalancerOptions:負載均衡選項(DownstreamHostAndPorts有多個的時候才能看到效果),有三種方式
LeastConnection : 將請求發往最空閒的那個服務器
RoundRobin :輪流發送
NoLoadBalance :不啓用負載均衡,總是發往第一個請求或者服務發現的那個服務器
GlobalConfiguration:顧名思義就是全局配置,此節點的配置允許覆蓋ReRoutes裏面的配置,你可以在這裏進行通用的一些配置信息。
OcelotDemo中添加Ocelot支持。
首先在OcelotDemo項目的Program.cs中加載上一步我們添加的Ocelot的配置文件,如下所示:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.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();
})
.UseUrls("http://localhost:1000")
.UseStartup<Startup>();
然後,在Startup.cs中,添加Ocelot服務並啓用Ocelot中間件,這裏你需要在Startup.cs文件中引入下面兩個命名空間:
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
然後,分別在ConfigureServices中註冊Ocelot服務以及Configure中啓用Ocelot中間件:
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot();//注入Ocelot服務
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseOcelot().Wait();//使用Ocelot中間件
app.UseMvc();
}
這時候,Ocelot的配置基本完成了,下面我們驗證下Ocelot有沒有正常工作,以及我們配置的負載均衡,有沒有起作用吧。
結合我們上面的配置,可以知道改造的目的就是爲了如下的測試,我們做出如下假設:
- 爲了驗證上游模板/{everything} 對應下游模板/api/{everything} 我們請求的路徑即爲http://localhost:1000/Values 並且把GoodApi以及GoodApi響應路徑分別設置爲:http://localhost:1001/api/Values ,http://localhost:1003/api/Values 並得到正確的響應
- 爲了驗證Ocelot項目起作用,我們請求ocelotDemo項目的路徑values,應該返回GoodApi,或者OrderApi項目中values控制器的值,而不是返回ocelotDemo中values控制器的值
- 爲了驗證Ocelot負載均衡起作用,我們連續訪問ocelotDemo項目的路徑values,則返回的結果應該是輪流返回GoodApi以及OrderApi的值。
下面我們利用 dotnet run
命令分別啓動三個項目,當然你也可以多項目啓動。然後訪問OcelotDemo項目的Url並訪問Values控制器,完整路徑“http://localhost:1000/Values”,看到
OcelotDemo的Url:http://localhost:1000
GoodApi的Url:http://localhost:1001
OrderApi的Url:http://localhost:1002
我們第一次訪問http://localhost:1000/Values 得到如下結果:
測試Ocelot項目以及負載均衡有沒有起作用
這裏,首先分別對三個項目的ValuesController控制器做如下改造:
OcelotDemo項目ValuesController中的Get方法改造如下:
[HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1 from Ocelot", "value2 from Ocelot" }; }
OrderApi項目中的ValuesController中的Get方法改造如下:
[HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1 from Order Api", "value2 from Order Api" }; }
GoodApi項目中的ValuesController中的Get方法改造如下:
[HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1 from Good Api", "value2 from Good Api" }; }
說明我們的假設1以及假設2都是沒問題的。也就是說我們的Ocelot已經在起作用了,而且根據上下游路由進行了映射。
接下來我們刷新下頁面,得到如下結果:
說明我們的假設3即Ocelot的負載均衡也起作用了。當然,你可以多刷新幾次,可以看到返回的結果在GoodApi與Order Api之間來回切換。因爲我們的負載均衡策略就是輪詢啊!
源碼鏈接
Github地址:https://github.com/yilezhu/OcelotDemo
最後
這篇文章主要是爲了讓記錄如何快速的開始使用Ocelot。關於Ocelot的配置很多都沒有描述,包括限流以及熔斷策略,以及多配置文件自動加載功能,等等。這個超出了快速開始的範圍,當然這些高級的用法會在下面的系列文章中會一一記錄。
本文使用的是Ocelot最新版本,爲了保持技術上的跟進,因此沒有使用上篇文章介紹的老版本,所以演示都是通過最新的ocelot版本來跟進的!
總結
本篇文章只是記錄了,如何快速的成功的使用ocelot,並進行了簡單的配置,配置中又引入了一個負載均衡的策略,最後通過代碼進行了相關的實現以及測試!關於其他的一些配置,我會在下面的文章中進行闡述。這裏只是對上篇文章“Ocelot簡易教程(二)之快速開始1”的補充!感謝大家的閱讀!