首页 > 其他分享 >NetCore Ocelot 之 Load Balancer

NetCore Ocelot 之 Load Balancer

时间:2023-10-08 18:33:07浏览次数:41  
标签:Load load Balancer balancer Ocelot services new your

Ocelot can load balance across available downstream services for each Route. This means you can scale your downstream services and Ocelot can use them effectively.

The Type of load balancer availble are:

   LeastConnection  - tracks which service are dealing with requests and sends new requests to services with least existing requests.The algorithm state is not distributed across a cluster of Ocelot's.

   RoundRobin - loops through available services and sends requests. The algorithm state is not distributed across a cluster of Ocelot's.

    NoLoadBalancer  -takes the first available service from config or service discovery.

    CookieStickySesssions - Uses a cookie to stick all requests to a specific server.

Please note that if you give more than one DownstreamHostAndPort or you are using a Service Discovery provider such as Consul and this returns more than one service then CookieStickSession uses round robin to select the next server. This is hard code at the moment but could be changed.

 "LoadBalancerOptions": {
        //"Type": "CustomRandomLoadBalancer"
        "Type": "CookieStickySessions",
        "Key": "ASP.NET_SessionId",
        "Expiry": 1800000
      }

In order to create and use a custom load balancer you can do the following. Below we setup a basic load balancing config and the Type is CustomLoadBalancer this is the name of a class we will setup to do load balancing.

{
      "DownstreamPathTemplate": "/api/service1",
      "DownstreamScheme": "https",
      "DownstreamHttpMethod": "Get",
      "UpstreamHttpMethod": [ "Options", "Get", "Post", "Put", "Delete" ],
      "UpstreamPathTemplate": "/Ocelot/service1",
      //"UpstreamHost": "localhost",//404 Not found
      "UseServiceDiscovery": true,
      "ServiceName": "serviceA",
      /*
      LeastConnection
      RoundRobin
      NoLoadBalance
      */
      "LoadBalancerOptions": {
        "Type": "CustomRandomLoadBalancer"
      },
      "RateLimitOptions": {
        "ClientWhiteList": [ "NoLimitedAPI" ],
        "EnableRateLimiting": true,
        "Period": "10s", //1s, 5m, 1h, 1d
        "PeriodTimespan": 10, //retry after n second/seconds
        "Limit": 3
      },
      "authenticationoptions": {
        "authenticationproviderkey": "authenticationkey",
        "allowedscopes": [ "apiscope1" ]
      },
      "Key": "service1",
      "Priority": 11
    }

Then you need to create a class that implements the ILoadBalancer interface. 

public class CustomRandomLoadBalancer : ILoadBalancer
{
        private readonly Func<Task<List<Service>>> _services;
        private readonly Object _lock = new object();
        private int _index;

        public CustomRandomLoadBalancer(Func<Task<List<Service>>> services)
        {
            _services = services;
        }

        public async Task<Response<ServiceHostAndPort>> Lease(HttpContext httpContext)
        {
            var services = await _services();
            if (services == null)
                return new ErrorResponse<ServiceHostAndPort>(new ErrorInvokingLoadBalancerCreator(new Exception("Load balance algorithm error.")));
            lock (_lock)
            {
                if (services.Count == 1)
                    return new OkResponse<ServiceHostAndPort>(services[0].HostAndPort);
                _index = new Random().Next(services.Count);
                return new OkResponse<ServiceHostAndPort>(services[_index].HostAndPort);
            }
        }

        public void Release(ServiceHostAndPort hostAndPort)
        {
        }
    }

Finally you need to register this class with Ocelot. I have used the most complex example below to show all of the data/types that can be passed into the factory that create load balancers.

Func<IServiceProvider, DownstreamRoute, IServiceDiscoveryProvider, CustomLoadBalancer> loadBalancerFactoryFunc = (serviceProvider, Route, serviceDiscoveryProvider) => new CustomLoadBalancer(serviceDiscoveryProvider.Get);

s.AddOcelot()
    .AddCustomLoadBalancer(loadBalancerFactoryFunc);

However there is a much simple example that will work the same.

builder.Services.AddOcelot()
    //.AddCacheManager(c => c.WithDictionaryHandle())// cache manager
    .AddSingletonDefinedAggregator<CustomAdvancedAggregator>()
    .AddCustomLoadBalancer((serviceProvider, route, serviceDiscoveryProvider) => new CustomRandomLoadBalancer(serviceDiscoveryProvider.Get))
    .AddConsul()
    .AddPolly();

When you enable custom load balancers Ocelot looks up your load balancer by its class name when it decides if it should do load balancing. If it finds a match it will use your laod balancer to laod balance. If Ocelot cannot match the load balancer type in your configuration with name of registered load balancer class then you will recieve a HTTP 500 internal error. If your load balancer factory throw an exception when Ocelot calls it you will receiver a Http 500 internal server error.

Remember if you specify no load balancer in your config Ocelot will not try and load balance.

The random custom load balancer e.g.

 

 

标签:Load,load,Balancer,balancer,Ocelot,services,new,your
From: https://www.cnblogs.com/qindy/p/17749856.html

相关文章

  • recursion is detected during loading of “cv2” binary extensions
    报错如下importError:ERROR:recursionisdetectedduringloadingof“cv2”binaryextensions.CheckOpenCVinstallation.使用版本linux需要使用无头版本4.7.0.72python3.8opencv-python==4.7.0.72;sys_platform!="linux"opencv-python-headless4.7.0.72;sys_p......
  • NetCore Ocelot 之 Authentication
    InordertoauthenticateRoutesandsubsequentlyuseanyofOcelot'sclaimsbasedfeaturessuchasauthorizationormodifyingtherequestwithvaluesfromthetoken.UsersmustregisterauthenticationservicesintheirStartup.csasusualbuttheypr......
  • Mysql 8.0 Navicat连接Mysql报错Authentication plugin ‘caching_sha2_password‘ ca
    1、终端登陆MySQL$mysql-uroot-ppassword#登入mysql2、修改账户密码加密规则并更新用户密码ALTERUSER'root'@'localhost'IDENTIFIEDBY'123456'PASSWORDEXPIRENEVER;#修改加密规则ALTERUSER'root'@'localhost'IDENTIFIEDWITHmysql_nat......
  • NetCore Ocelot 之 Rate Limiting
    Ocelotsupportsratelimitingofupstreamrequestssothatyourdownstreamservicesdonotbecomeoverloaded.OKsotogetratelimitingworkingforaRouteyouneedtoaddthefollowingjsontoit."RateLimitOptions":{"ClientWhi......
  • [极客大挑战 2019]Upload
    原理文件上传MIME和文件头的检测php的多种后缀木马连接解题过程进入靶场,应该就是上传漏洞然后连接木马即可。先上传个正常文件名的文件然后抓包,我上传个正常jpg文件还冤枉我??先把文件内容删了。MIME信息和文件头信息换换换成png还是不行,试试gif格式终于可以了--,现在给......
  • Error while loading conda entry point: conda-libmamba-solver (libarchive.so.19:
    本人使用centos:7.6.1810及Miniconda3-py311_23.5.2-0-Linux-x86_64默认状态下应该没有这个问题。当在使用conda下载包时,如果不小心更新了涉及conda-libmamba-solver和libarchive的包,就可能会导致这个报错消息出现。Errorwhileloadingcondaentrypoint:conda-libmamb......
  • [架构之路-25]:目标系统 - 系统软件 - bootloader uboot内存映射与启动流程
    原文:https://blog.csdn.net/HiWangWenBing/article/details/127062057目录第1章uboot概述1.1概述1.2内存映射(案例)1.3uboot在嵌入式系统启动中的位置第2章uboot启动流程(源码分析)2.1入口函数:_start2.3执行流程(文字描述)2.4初始化过程第3章uboot如何加载内核3.1v......
  • Unable to load site GPT
     001、问题 GPT官网无法打开,如下:  002、解决方法   参考:https://laowangblog.com/chatgpt-unable-to-load-site.html.......
  • S32Kxxx bootloader 之 LIN UDS bootloader
    了解更多关于bootloader的C语言实现,请加我Q扣:1273623966(验证信息请填bootloader),欢迎咨询或定制bootloader(在线升级程序)。LIN总线是汽车ECU使用比较多的一种总线,车灯,车门,汽车空调控制面板等等ECU都有在使用.而这些ECU离线升级时,就需要使用到LINbootloader,O......
  • Module build failed (from ./node_modules/css-loader/dist/cjs.js): CssSyntaxError
    问题描述在webpack的时候报错ERRORin./packages/theme-chalk/mixins/mixins.scss(./node_modules/css-loader/dist/cjs.js!./packages/theme-chalk/mixins/mixins.scss)Modulebuildfailed(from./node_modules/css-loader/dist/cjs.js):CssSyntaxError(14:8)......