微服务入门08 Ocelot

介绍

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也能做集群

posted @ 2018-09-22 17:15  Amayer  阅读(367)  评论(0编辑  收藏  举报