Ribbon load Balancing mechanism (custom load balancing rules)

Source: Internet
Author: User

Ribbon Load Balancing mechanism

In the previous chapter, "Introduction and construction of the Ribbon framework (no integration with Springcloud, independent use)" introduced the Ribbon Framework and construction use, then in this chapter will talk about the Ribbon load balancing mechanism, the following rules of the author will be easy to understand the introduction to everyone.

Ribbon built-in load balancing rules

1. Roundrobinrule

Select a server by simply polling the list of services
2. availabilityfilteringrule
The following two types of servers are ignored and will not be selected.
2.2 If the connection fails 3 times by default, the server will be set to a "short-circuit" state, which will last for 30 seconds. If you can't connect, the duration of this state will continue to increase.
# Number of failed connections, default is 3 times
Niws.loadbalancer.<clientname>.connectionfailurecountthreshold
# One instance can keep the maximum period of "unavailable" state, default to 30 seconds
Niws.loadbalancer.<clientname>.circuittripmaxtimeoutseconds
# Maximum number of concurrent
<clientname>.<clientconfignamespace>. Activeconnectionslimit
3. Weightedrsponsetimerule

Each server is given a weight value, the longer the server response time, the less weight of the server, the weight may determine the choice of the server (there is random)
4. Zoneavoidancerule

Server selection based on regional, available servers, classification of servers using zone
5. Bastavailablerule

Ignore those short-circuiting servers and select servers with lower number of concurrent
6. Randomrule

Randomly select one of the available servers
7. Retryrule

It is a selection logic with a retry mechanism

Other configurations
Nfloadbalancerpingclassname: Check if the server is alive
Nfloadbalanceclassname: Specifies the implementation class for the load balancer that you can use to customize the load balancer
Niwsserverlistclassname: The processing class for the server list that maintains the server list
Nisserverlistfilterclassname: Server Intercept class

Here I will not give you all the configuration, interested can go to the official website of the wiki to see:https://github.com/Netflix/ribbon

First, you need to create a ribbon server, even in the previous chapter, but there are some lazy little friends (secretly tell everyone, I am also one of them, I want to directly copy paste (* ^_^ *)).

1: Create the Ribbon server (a simple springboot program)

Pom.xml

<dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>        <version>1.5.7.RELEASE</version>    </dependency></dependencies>

To facilitate the Ribbon client test, build an entity class here: Person.java

 Public classPerson {PrivateString URL;//server URL for processing requests    PrivateString message;//Prompt Information         PublicString GetUrl () {returnURL; }     Public voidseturl (String url) { This. url =URL; }     PublicString getMessage () {returnmessage; }     Public voidsetmessage (String message) { This. Message =message; }}

Personcontroller.java

@RestController  Public class PersonController {    @RequestMapping (value= "/getperson", Method=requestmethod.get, produces=  Mediatype.application_json_value)    public person  Getperson (httpservletrequest request) {         New person ();        P.setmessage ("request succeeded");        P.seturl (Request.getrequesturl (). toString ());         return p;    }}

Startup class: Application.java (because to test load balancing, all this needs to start multiple services, the following configuration starts by manually entering the port number)

@SpringBootApplication  Public class Application {    publicstaticvoid  main (string[] args) {        new  Scanner (system.in);         = scan.nextline ();         New Springapplicationbuilder (Application.  Class). Properties ("server.port=" +port). Run (args);}    }

This boot starts with ports: 8080, 8081, and later we configure the client unified test (after configuration, start the service)

2: Create Ribbon Client

Only the core and client dependencies can be introduced in Pom.xml.

<dependency>    <groupId>com.netflix.ribbon</groupId>    <artifactId>ribbon-core< /artifactid>    <version>2.2.5</version></dependency><dependency>    <groupid >com.netflix.ribbon</groupId>    <artifactId>ribbon-httpclient</artifactId>    < Version>2.2.5</version></dependency>

The above configuration and the contents of the previous chapter is exactly the same, then we will pay attention to the next content, but also the focus of this explanation. (This case has poll + custom load balancer + Access Service)

Use the default polling rule


Public Static voidMain (string[] args)throwsException {//Create a Load Balancer objectIloadbalancer lb =NewBaseloadbalancer (); //set up a server listlist<server> servers =NewArraylist<server>(); Servers.add (NewServer ("localhost", 8080)); Servers.add (NewServer ("localhost", 8081)); //Add a list of services to the load Balancerlb.addservers (servers); //Default rule: Polling for(inti=0; i<10; i++) {Server s= Lb.chooseserver (NULL); System.out.println (s); }}

Using a custom Load balancer

/*** * Custom Load balancer, here need to implement "IRule" interface * such as Port 8081 server is new buy, do not want it to handle too many tasks, then can use random number to control its traffic *@authorLPX **/ Public classMyruleImplementsirule{PrivateIloadbalancer lb;//declaring the Load Balancer interface@Override PublicServer Choose (Object key) {//Get Server Listlist<server> servers =lb.getallservers (); //Production random numberRandom r =NewRandom (); intRand = R.nextint (10); if(Rand > 7){            returnGetserverbyport (Servers, 8081); }Else{            returnGetserverbyport (servers, 8080); }    }    /*** Returns the service object according to the incoming port number *@paramServers *@paramPort *@return     */    PrivateServer Getserverbyport (list<server> servers,intPort) {         for(Server s:servers) {if(S.getport () = =Port) {                returns; }        }        return NULL; } @Override Public voidsetloadbalancer (iloadbalancer lb) { This. lb =lb; } @Override Publiciloadbalancer Getloadbalancer () {return  This. LB; }}
 Public Static voidMain (string[] args)throwsException {//Create a Load balancerBaseloadbalancer BLB =NewBaseloadbalancer (); //Create a custom load balancerMyrule Myrule =NewMyrule (); //set up a load balancerMyrule.setloadbalancer (BLB); //set up load balancer rulesBlb.setrule (Myrule); //set up a server listlist<server> servers =NewArraylist<server>(); Servers.add (NewServer ("localhost", 8080)); Servers.add (NewServer ("localhost", 8081));    Blb.setserverslist (servers);  for(inti=0; i<10; i++) {Server s= Blb.chooseserver (NULL);    System.out.println (s); }}

Accessing services using a custom load balancer

 Public Static voidMain (string[] args)throwsException {//Write Service listConfigurationmanager.getconfiginstance (). SetProperty ("My-client.ribbon.listofservers", "localhost:8080, localhost:8081 "); //Configure rule ClassesConfigurationmanager.getconfiginstance (). SetProperty ("My-client.ribbon.nfloadbalancerruleclassname", MyRule.class. GetName ()); //Output Service ListSYSTEM.OUT.PRINTLN ("Service list:" + configurationmanager.getconfiginstance (). GetProperty (" My-client.ribbon.listofservers ")); //Create clientRestclient client = (restclient) clientfactory.getnamedclient ("My-client"); //Create a Request objectHttpRequest request = Httprequest.newbuilder (). Uri (NewURI ("/getperson") . Build (); //Multiple Access tests     for(inti = 0; I < 10; i++) {        //Create a Response objectHttpResponse response =Client.executewithloadbalancer (Request); //Receive Request ResultsString json = Response.getentity (string.class); //Print ResultsSystem.out.println (JSON); }}

OK, the above is the entire content of this article (load Balancing rules mechanism + custom load balancing rules + Access services), if the author has written the wrong place also hope everyone put forward, crab crab!!!

Ribbon load Balancing mechanism (custom load balancing rules)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.