Springcloud's Ribbon

Source: Internet
Author: User

A: What is the ribbon?

The Ribbon is an open source project by Netflix that provides a client-side software load-balancing algorithm that connects Netflix's middle-tier services. The Ribbon client component provides a complete set of configuration items such as connection timeouts, retries, and so on. Simply put, all the machines behind load Balancer (lb) are listed in the configuration file, and the Ribbon automatically helps you to connect the machines based on certain rules (such as simple polling, then connecting, and so on). It is also easy to implement a custom load balancing algorithm using the Ribbon.

II: LB Program classification

The current mainstream LB scheme can be divided into two categories: a centralized lb, which is the use of a separate lb facility between the consumer and provider of the service (either hardware, such as F5, or software, such as Nginx), which is responsible for forwarding the access request through some policy to the provider of the service, and the other in-process lb, Integrating the LB logic into the consumer, the consumer learns from the service registry which addresses are available and then chooses a suitable server from those addresses themselves. The ribbon belongs to the latter, which is just a class library, integrated in the consumer process, where the consumer obtains the address of the service provider.

Three: The main components and workflow of the Ribbon

The core components of the Ribbon, all of which are interface types, have the following:

ServerList: Used to get the address list. It can be either static (providing a fixed set of addresses) or dynamic (the list of addresses is queried periodically from the registry).

Serverlistfilter: Used only when using dynamic serverlist to use a certain policy in the original list of services to remove a subset of addresses.

IRule: Select a final service address as the LB result. The selection strategy has polling, weighting based on response time, breaker (when Hystrix is available), etc.

The ribbon prefers to use serverlist to get a list of all available services at work, then serverlistfilter a portion of the address, and finally selects a server as the final result in the remaining address through Irule.

IV: Introduction to the main load balancing strategy provided by the Ribbon

1: Simple poll load balancer (Roundrobin): The request is polled in turn to schedule different servers, that is, each time the schedule executes i = (i + 1) mod n, and I select the first server.

2: Random Load balancer: Randomly select the server with the UP state

3: Weighted response time Load balancer (weightedresponsetime): Assigns a weight according to the corresponding time, the longer the corresponding time, the smaller the weight, the lower the likelihood of being selected.

4: Zone-aware polling load balancing (zoneavoidancerule): Compound to determine the performance of the server area and server availability Select Server

Ribbon self-load balancing strategy comparison

V: Ribbon used alone

Create a MAVEN project with the following name Ribbon_client,pom:

<dependencies>        <dependency>            <groupId>com.netflix.ribbon</groupId>            < Artifactid>ribbon-core</artifactid>            <version>2.2.  0</version>        </dependency>        <dependency>            <groupid>com.netflix.ribbon </groupId>            <artifactId>ribbon-httpclient</artifactId>            <version>2.2 . 0</version>        </dependency>    </dependencies>

Sample-client.properties configuration file

# Max number of Retriessample-client.ribbon.maxautoretries=1# Max Number of next servers to retry (excluding the first server) sample-client.ribbon.maxautoretriesnextserver=1# Whether All operations can is retried for  ThisClientsample-client.ribbon.oktoretryonalloperations=true# Interval to refresh the server list fromThe sourcesample-client.ribbon.serverlistrefreshinterval= -# Connect Timeout used by Apache Httpclientsample-client.ribbon.connecttimeout= the# Read Timeout used by Apache Httpclientsample-client.ribbon.readtimeout= the# Initial List of servers, can be changed via ArchaiusDynamicProperty at Runtimesample-client.ribbon.listofservers=www.sohu.com: theWww.163. com: the, www.sina.com.cn: theSample-client.ribbon.enableprimeconnections=true

Ribbonmain Code

Import Java.net.uri;import Com.netflix.client.clientfactory;import com.netflix.client.http.httprequest;import Com.netflix.client.http.httpresponse;import Com.netflix.config.configurationmanager;import Com.netflix.loadbalancer.zoneawareloadbalancer;import com.netflix.niws.client.http.RestClient; Public classRibbonmain { Public Static voidMain (string[] args) throws Exception {configurationmanager.loadpropertiesfromresources ("sample-client.properties"); System. out. println (Configurationmanager.getconfiginstance (). GetProperty ("sample-client.ribbon.listofservers")); Restclient Client= (restclient) clientfactory.getnamedclient ("sample-client"); HttpRequest Request= Httprequest.newbuilder (). Uri (NewURI ("/") . Build ();  for(inti =0; I <4; i + +) {HttpResponse response=Client.executewithloadbalancer (Request); System. out. println ("Status for URI:"+ Response.getrequesteduri () +"is :"+response.getstatus ()); } zoneawareloadbalancer lb=(Zoneawareloadbalancer) client.getloadbalancer (); System. out. println (Lb.getloadbalancerstats ()); Configurationmanager.getconfiginstance (). SetProperty ("sample-client.ribbon.listofservers","ccblog.cn:80,www.linkedin.com:80"); System. out. println ("Changing Servers ..."); Thread.Sleep ( the);  for(inti =0; I <3; i + +) {HttpResponse response=Client.executewithloadbalancer (Request); System. out. println ("Status for URI:"+ Response.getrequesteduri () +"is :"+response.getstatus ()); } System. out. println (Lb.getloadbalancerstats ()); }  }

Code parsing

Load properties using Archaius ConfigurationManager;

Create a client and load balancer using Clientfactory;

Use Builder to build HTTP requests. Note that we only support the path of the "/" section of the URI, and once the server is selected by the load balancer, the complete URI is computed by the client;

Call API Client.executewithloadbalancer (), not exeucte () API;

Dynamic remediation of server pools in configuration;

Wait for the server list to refresh (the refresh interval defined in the configuration file is 3 seconds);

Print out server statistics for the load Balancer record.

Six: Ribbon combined with Eureka use

Create a MAVEN project Eureka_ribbon_client the project start-up and related configuration dependencies:

<parent> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-parent</artifactid> <version>1.4.3. Release</version> <relativePath/> <!--lookup Parent from Repository--></parent><dependencies> <dependency> <groupid>org.springframework.clou d</groupid> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency> <de Pendency> <groupId>org.springframework.cloud</groupId> <artifactid>spring-cloud-starter -eureka</artifactid> </dependency> <dependency> <groupId>org.springframework.boot< /groupid> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency&        Gt <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-test</ Artifactid> <scope>test</scope> </dependency></dependencies><dependencymanagement&    Gt <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> < Artifactid>spriNg-cloud-dependencies</artifactid> <version>Brixton.RELEASE</version> <type>pom</ type> <scope>import</scope> </dependency> </dependencies></dependencymanagement >

In the application main class, the Discovery service capability is added through @enablediscoveryclient annotations. Create a Resttemplate instance and turn on the load balancing capability with @loadbalanced annotations.

@SpringBootApplication @enablediscoveryclient  Public class ribbonapplication {    @Bean    @LoadBalanced    resttemplate resttemplate () {        return New resttemplate ();    }      Public Static void Main (string[] args) {        springapplication.run (ribbonapplication. class , args);}    }

Create Consumercontroller to consume SERVICE01 's GetUser service. Invoking a service by direct resttemplate

@RestController  Public class Consumercontroller {     @Autowired    resttemplate resttemplate;      " /getuserinfo ", method = requestmethod.get)    public  String Add () {        return resttemplate.getforentity ("http://biz-service-0/getuser", String.  Class). GetBody ();    }}

The ribbon is actually a soft-load-balanced client component that can be used in conjunction with other client-requested clients, and Eureka is just one example.

Springcloud's Ribbon

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.