The Ribbon of Springcloud learning

Source: Internet
Author: User
Tags format definition

One. Load Balancing with Ribbon
    1. Load balancing, in the cluster is a very common "noun", as the name implies is based on a certain algorithm to allocate the request to the corresponding service node, the common algorithm has the following:
    • Polling: All requests are distributed sequentially to each application server, and each server needs to process the same number of requests, for scenarios where all server hardware is the same
    • Random method: The request is randomly assigned to each application server, in many cases, this scheme is very simple and practical.
    • Source address hash (hash) method: The IP address of the requested source is hashed to get the corresponding server, so that requests from the same IP are always processed on the same server
    • Weighted method: According to the application server configuration, according to the weight of the request distribution to each server, of course, high-performance server allocation of higher weights
    • Minimum number of connections (Least Connections) Method: Calculates the number of connections each application server is processing, distributes new requests to the least connected servers, which is arguably the most consistent algorithm for load balancing definitions

2. The Ribbon is a load-balanced client framework provided by Netfix Corporation, which integrates well with open source products such as the company's Eureka Feign Hystrix, with the Ribbon framework having the following features:

      • Load Balancing
      • Fault tolerant
      • Multi-Protocol (HTTP, TCP, UDP) supports asynchronous and reactive models.
      • Cache and Batch Processing

Two. Ribbon use Mode 1. First we define the service (here is Order-server) Note the two configuration files in the service

Application.properties

  

#应用程序名称spring. Application.Name=order-server# specifying config-address of the Server service Spring.cloud.config.uri=http://localhost:8888#spring. profiles.active=local# is the currently active environment #spring.cloud.config.profile=${spring.profiles.active}spring.cloud.config.label=master# Registration Center address Eureka.client.service-url.defaultzone=http://Localhost:8000/eureka#服务端口号server. Port=8001#management. Endpoint.health.show-details=always#management.endpoint.hystrix.health.enabled=true# http://Localhost:8888/{spring.application.name}/{spring.cloud.config.profile}/{label}
View Code

Application-multi.properties

spring.application.name=order-servereureka.client.service-url.defaultzone=http://  Localhost:8000/eurekaserver.port=8011management.endpoint.health.show-details=  Alwaysmanagement.endpoints.web.base-path=/management.endpoints.web.exposure.include= Health, beans,info# http://localhost:8888/{spring.application.name}/{spring.cloud.config.profile}/{ Label}
View Code

Here we focus on the Spring.application.name configuration and set different port numbers

  

2. Set the Startup class configuration item in Idea

Note that the Single instance check box is ticked off active profiles is the setting of the currently active environment, which is started after configuration is complete. Orderapplication Service two times

3. Create a new project Ribbon-project and add dependencies
Compile (' Org.springframework.cloud:spring-cloud-starter-netflix-ribbon ')

4. Add configuration items in Application.properties
Order.ribbon.listofservers=http://localhost:8001,http://localhost: 8011 order.ribbon.connecttimeout=3000order.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.randomrule
View Code

Attention:

    1. The format definition in this: <client-name>.<namespace>.<property-value>=<value>, where client-name represents the client name, In the future we will get the client object according to this name.
    2. Namespace default namespace for Ribbon
    3. Property-value we can refer to: Enum commonclientconfigkey. Where Listofservers configuration is our Order-server service address, of course, we can not do any configuration, then the Ribbon will give us the default configuration (refer to: Defaultconfigclientimpl), If you do not specify a client name, the configuration applies to all clients.
    4. We can specify a load balancing policy in the form of: <clientName>.<clientConfigNameSpace>.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.<className>  classname Value: Bestavailablerule (), Randomrule (Random), Roundrobbinrule (polling), Weightedresponsetimerule (weight response time)
5. Writing the client request code
 PackageCom.bdqn.lyrk.ribbon.study;Importcom.netflix.client.ClientFactory;Importcom.netflix.client.http.HttpRequest;ImportCom.netflix.client.http.HttpResponse;ImportCom.netflix.config.ConfigurationManager;Importcom.netflix.niws.client.http.RestClient; Public classribbonapplication { Public Static voidMain (string[] args)throwsException {//Load configuration fileConfigurationmanager.loadpropertiesfromresources ("Application.properties"); Restclient restclient= (restclient) clientfactory.getnamedclient ("Order"); HttpRequest HttpRequest= Httprequest.newbuilder (). Uri ("/ORDERID/1"). build ();  for(inti = 0; I < 5; i++) {HttpResponse response=Restclient.executewithloadbalancer (HttpRequest); System.out.println (Response.getentity (String.class)); }    }}
View Code

6. Service Side Please refer to: Springcloud Learning feign end of code example three. Ribbon1 in Springcloud) use @loadblanced annotations and Feignclient

After adding @loadblanced annotations on Resttemplate, the hero behind the scenes became loadbalancerclient, At this point, the Loadbalancerinterceptor Interceptor object is created to join the Resttemplate interceptor stack, and you can see for yourself the following code example:

  

   @Bean    @LoadBalanced    resttemplate resttemplate () {returnnew resttemplate () ;}
View Code

2) Use Discoveryclient

This object is spring for us to provide good, we can use it by @autowired.

3) @RibbonClient and @LoadBalanced

Springcloud provides @ribbonclient annotations to create your own defined ribbonclient, and the first contact is easily confused with @loadbalanced annotations, so here's a quick explanation:

@LoadBalced is primarily marked on resttemplate, then resttemplate will use it RibbonLoadBalancerClient to get the service

@RibbonClient is primarily used to configure the Ribbonclient client, and this annotation is not required to be configured in our service discovery, if we use the service discovery mechanism in Springcloud, At this point Springcloud will provide us with the default ribbon configuration, even if we do not need to configure @ribbonclient, but when we need to define our own ribbonclient or impractical service discovery, Then we can use @ribbonclient annotations

Examples of Use:

Add the following annotations to our startup class

@RibbonClient (name = "MyService")

Then we do the following configuration in Application.properties:

 

Myservice.ribbon.eureka.enabled=falsemyservice.ribbon.listOfServers=http://   http://localhost: 5001
View Code

  

The Ribbon of Springcloud learning

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.