.Net Core-Ocelot的使用一:基本配置(负载均衡)

1、NuGet安装:Ocelot
2、添加引用
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

Ocelot的主要功能是接收传入的http请求并将它们转发到下游服务。

一、Ocelot.Json配置

{
  "ReRoutes": [ //ReRoutes:一个请求路由到另一个请求
    {
      "DownstreamPathTemplate": "/api/{everything}", //将请求转发到的URL
      "DownstreamScheme": "http", //将请求转发到的URL
      "DownstreamHostAndPorts": [ //将请求转发到的URL 
        //通常它只包含一个条目,但有时您可能希望向下游服务发送负载平衡请求,Ocelot允许您添加多个条目,然后选择一个负载平衡器。
        {
          "Host": "localhost",//主机
          "Port": 3003//端口
        },
        {
          "Host": "localhost",
          "Port": 3004
        }
      ],
      "UpstreamPathTemplate": "/{everything}", //标识给定请求使用哪个DownstreamPathTemplate的URL
      "UpstreamHttpMethod": [ "Get" ], //以便Ocelot可以区分对同一URL使用不同HTTP动词的请求
      "ReRouteIsCaseSensitive": true //默认的ReRouting配置不区分大小写,为true后将区分大小写
      //服务发现设置:Ocelot将从服务发现提供程序中查找下游主机和端口,并在所有可用服务中进行负载平衡请求。
      "LoadBalancerOptions": { //负载均衡
        "Type": "RoundRobin" //LeastConnection
      }
    }
  ],
  "GlobalConfiguration": {
  }
}

/* 最基本的ocelot.json
{
    //处理上游请求对象
    "ReRoutes": [],

    //
    "GlobalConfiguration": {}
}*/

二、Program配置

        public static void Main(string[] args)
        {
            #region  Ocelot
            new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    //配置多个特定环境文件
                    config
                    .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                    //AddJsonFile可配置多个配置文件
                    .AddJsonFile("appsettings.json", true, true)
                    //Ocelot需要HostingEnvironment,因此它知道要从算法中排除任何特定的环境。
                    .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                    .AddJsonFile("ocelot.json")
                    .AddEnvironmentVariables();
                })
                .ConfigureServices(s => {
                    //最重要!!!
                    s.AddOcelot();//添加ocelot服务
                })
                .ConfigureLogging((hostingContext, logging) => {

                })
                .UseIISIntegration()
                .UseUrls("http://localhost:1000") //客户端访问地址
                .Configure(app => {
                    app.UseOcelot().Wait();//设置所有ocelot中间件
                })
                .Build()
                .Run();
            #endregion

            CreateHostBuilder(args).Build().Run();
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值