.Netcore 2.0 Ocelot Api網關教程(1)- 入門

Ocelot(Github)
Ocelot官方文檔(英文)
本文不會介紹Api網關是什么以及Ocelot能干什么
需要對Api網關及Ocelot有一定的理論了解

開始使用Ocelot搭建一個入門級Api網關

1.新建3個WebApi項目,分別命名為OcelotGetway、WebApiA、WebApiB


webapi項目.png
  • OcelotGetway項目用于做Api網關
  • WebApiA、WebApiB作為兩個api接口服務

2.在OcelotGetway項目的Nuget包管理器中搜索Ocelot并安裝

Nuget包管理器.png

或者在程序包管理器中輸入
Install-Package Ocelot安裝

3.在OcelotGetway項目中新建json文件并命名為configuration.json在VS中右鍵修改為“始終復制”


configuration.json.png

4.編輯configuration.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" ]
    }
  ]
}

5.修改OcelotGetway項目的Startup類如下

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

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

public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    await app.UseOcelot();

    app.UseMvc();
}

6.修改WebApiA和WebApiB項目的ValuesController分別為

[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1 from webapi A", "value2 from webapi A" };
}
[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1 from webapi B", "value2 from webapi B" };
}

7.編輯Properties目錄下的launchSettings.json文件中的applicationUrl(每個文件中有兩個,只改下邊的就可以)


launchSettings.json.png

分別設置3個項目的applicationUrl為:

8.分別運行WebApiA、WebApiB、OcelotGetway
瀏覽器分別訪問
http://localhost:5000/webapia/values
http://localhost:5000/webapib/values

運行效果.png

源碼下載

完,下一篇將介紹路由

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容