.NET Core微服务开发网关篇-ocelot

通过上篇我们知道,网关是外部访问的统一入口,本文采用Ocelot作为Api网关。

环境要求:

  • vs2019

  • .NetCore3.1

  • Ocelot16.0.1

创建一个产品服务Api站点(AAStore.ProductCatalog.Api)

添加一个ProductController

  [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        [HttpGet(template:"Get")]
        public string GetProductById()
        {
            return "Product service";
        }
    }

运行浏览

然后再创建一个订单服务Api站点(AAStore.Orde.Api)

添加一个OrderController

   [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        [HttpGet(template:"Get")]
        public string GetOrder()
        {
            return "Order Service";
        }
    }

运行浏览

两个服务已经已经准备好了,最后创建一个网关站点(AAStore.WebApiGateway)

  • 安装Ocelot

创建一个json配置文件(ocelot.json)

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/Product/get",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8081
        }
      ],
      "UpstreamPathTemplate": "/api/Product/{everything}",
      "UpstreamHttpMethod": [ "Get" ]
    },
    {
      "DownstreamPathTemplate": "/api/Order/get",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8082
        }
      ],
      "UpstreamPathTemplate": "/api/Order/get",
      "UpstreamHttpMethod": [ "Get" ]
    }
  ]
}

ocelot api网关的主要功能是接收传入的HTTP请求并将其转发到下游服务,目前作为一个HTTP请求。Ocelot将一个请求到另一个请求的路由描述为Routes。

DownstreamPathTemplate、Scheme 和 DownstreamHostAndPorts 构成要将此请求转发到的内部微服务 URL。

端口是服务使用的内部端口。使用容器时,在其 dockerfile 中指定端口。Host 是一个服务名称,取决于使用的服务名称解析。使用 docker-compose 时,服务名称由 Docker 主机提供,它使用 docker-compose 文件中提供的服务名称。如果使用 Kubernetes 或 Service Fabric 等业务流程协调程序,则应通过每个业务流程协调程序提供的 DNS 或名称解析来解析该名称。

DownstreamHostAndPorts 是一个数组,包含要将请求转发到的任何下游服务的主机和端口。通常这只包含一个条目,但有时可能想要将均衡请求加载到下游服务,而通过 Ocelot 即可添加多个条目,然后选择负载均衡器。但是如果使用 Azure 和任何业务流程协调程序,那么通过云和业务流程协调程序基础结构进行负载均衡可能会更好。

UpstreamPathTemplate 是一个 URL,Ocelot 将其用来识别用于客户端中给定请求的 DownstreamPathTemplate。最后,使用了 UpstreamHttpMethod,因此 Ocelot 可区分对相同 URL 的不同的请求(GET、POST、PUT)。

注意: ocelot16.x版本之后的配置节点写为Routes,而非ReRoutes 否则会报错(Failed to mat ch Route configuration for upstream path)。

  • 在Program.cs 通过AddJsonFile方法向生成器提供ocelot.json文件、添加Ocelot服务(AddOcelot)和添加ocelot中间件(UseOcelot)
    .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
                       {
                           config
                           .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                           .AddJsonFile("ocelot.json")
                           .AddEnvironmentVariables();
                           ;
                       })
                    .ConfigureServices(services =>
                    {
                        services.AddOcelot();
                        services.AddHttpContextAccessor();
                      
                    })
                    .Configure(app =>
                    {
                        app.UseOcelot().Wait();
                    });
                });

然后运行网关,通过网关访问产品、订单微服务:

如果运气好的话,跟着一步一步做,你也可以运行成功。当然ocelot还有很多功能如:路由、请求聚合、服务发现、WebSockets、认证、授权、LB、K8S、限流、熔断等等。

参考//docs.microsoft.com/zh-cn/dotnet/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-with-ocelot