Ocelot 新手上路


 

新手上路,老司機請多多包含!Ocelot 在博園里文章特別多,但是按照其中一篇文章教程,如果經驗很少或者小白,是沒法將程序跑向博主的結果.

因此總結下     參考多篇文章,終於達到預期效果。

 Ocelot   目標是使用.NET運行微服務/面向服務架構,我們需要一個統一的入口進入我們的服務,提供監控、鑒權、負載均衡等機制,也可以通過編寫中間件的形式,來擴展Ocelot的功能。  Ocelot是一堆特定順序的中間件。

 Ocelot開源地址:https://github.com/TomPallister/Ocelot

 

 

 

分別創建三個API

1.ApiGateway

2.WebApiA

3.WebApiB

 

 

以 APIGateway 項目 Nuget控制台,執行Ocelot安裝。

PM>Install-Package Ocelot    按回車等待安裝

如果看到這種情況  恭喜你   環境基本就緒  咱們開始走上編碼

 

 

1、APIGateway修改Startup

 
         

public class Startup
{

 
         


public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

 
         


public IConfiguration Configuration { get; }

 
         


// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

 
         

services.AddMvc();
services.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("configuration.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();

 
         

}

 
         

}

 

添加命名空間

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

 

3.ocelot.json 添加json

配置如下:

{
"ReRoutes": [ { "DownstreamPathTemplate": "/api/values", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5001 } ], "UpstreamPathTemplate": "/webapia/values", "UpstreamHttpMethod": [ "Get" ] }, { "DownstreamPathTemplate": "/api/values", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5002 } ], "UpstreamPathTemplate": "/webapib/values", "UpstreamHttpMethod": [ "Get" ] } ] }

 

4.分別修改   launchSettings.json

1.ApiGateway   5000

2.WebApiA        5001

3.WebApiB        5002

 

修改兩個地方就好

 

 

 最后設置啟動項   鼠標  選中解決方案  右鍵  選擇設置啟動項

 

 

配置完成  看看效果F5 跑起來

大家會發現  為什么

http://localhost:5000/api/values  報錯了

那是因為我們配置

 

因此這個地方  訪問咱們需要換一個鏈接

http://localhost:5000/webapib/values

http://localhost:5000/webapia/values

 

 看步驟大家應該就能猜到為什么會這樣運行,具體原理  可以看博園中大神們的注解


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM