基于netcore的微服务——Ocelot结合Consul配置文件(4)

引入包

    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
    <PackageReference Include="Ocelot" Version="7.0.8" />

一.只使用Ocelot

当只使用Ocelot需要对每台服务器都进行配置,会很麻烦

{
  "ReRoutes": [
    {
      //Ocelot转发     到本地的5001端口的地址     ...../MsgService/abc   ----》  localhost:5001/api/abc
      "DownstreamPathTemplate": "/api/{url}",
      //请求的方式
      "DownstreamScheme": "http",
      //请求的主机和端口
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      //客户端请求的路由
      "UpstreamPathTemplate": "/MsgService/{url}",
      //允许的请求方式
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }
  ]
}

二、结合Consul

结合Consul使用,不用去再一次把每台服务器配置一遍,
只需要结合Consul就能一键化配置

{
  "ReRoutes": [
    {
      //Ocelot转发     到本地的5001端口的地址     ...../MsgService/abc   ----》  localhost:5001/api/abc
      "DownstreamPathTemplate": "/api/{url}",
      //请求的方式
      "DownstreamScheme": "http",
      //请求的服务名
      "ServiceName": "MsgService",
      "LoadBalancerOptions": {
        //对于被发现服务器的使用方式
        "Type": "RoundRobin"
      },
      //开启服务发现
      "UseServiceDiscovery": true,
      //客户端请求的路由
      "UpstreamPathTemplate": "/MsgService/{url}",
      //允许的请求方式
      "UpstreamHttpMethod": [ "Get", "Post" ]
    },
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "ServiceName": "ProductService",
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      },
      "UseServiceDiscovery": true,
      "UpstreamPathTemplate": "/ProductService/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }
  ],
  //全局配置Consul服务器
  "GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
      "Host": "localhost",
      "Port": 8500
    }
  }
}

posted @ 2022-05-23 11:13  有诗亦有远方  阅读(22)  评论(0)    收藏  举报  来源