1. 程式人生 > >微服務入門08 Ocelot

微服務入門08 Ocelot

port 服務器 upstream eap ref tin oid sta 入門

介紹

Ocelot是一個用.NET Core實現並且開源的API網關


簡單的來說Ocelot是一堆的asp.net core middleware組成的一個管道。當它拿到請求之後會用一個request builder來構造一個HttpRequestMessage發到下遊的真實服務器,等下遊的服務返回response之後再由一個middleware將它返回的HttpResponseMessage映射到HttpResponse上。

引用自騰飛博客


安裝

Install-Package Ocelot
public void ConfigureServices(IServiceCollection services)
    {
        services.AddOcelot(Configuration);
    }

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

手動服務發現

新建配置json

{
  "ReRoutes": [
    //兩個路由規則
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      //目標地址
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/MsgService/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ]
    },
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5003
        }
      ],
      "UpstreamPathTemplate": "/ProductService/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }
  ]
}
.ConfigureAppConfiguration((hostingContext, builder) => {
            builder.AddJsonFile("configuration.json", false, true);
        })

ocelot本質的作用上就是一個微服務管理者,外部想要訪問某個微服務,就要通過這個網關,由ocelet決定訪問哪個微服務,並將結果返回

原來的訪問地址 http://localhost:5003/api/product/1

新訪問 http://localhost:8888/ProductService/product/1

ocelot搭配consul

ocelot也能做集群

微服務入門08 Ocelot