Spring Cloud customer service side load Balancer Ribbon

Source: Internet
Author: User

First, Introduction

The Spring Cloud Ribbon is a client-side load balancing tool based on HTTP and TCP, which is based on the Netflix Ribbon. It is not deployed independently, like a service registry, configuration center, API Gateway, but it almost exists in every microservices infrastructure. The declarative service invocation, which includes the preceding provision, is also implemented based on the Ribbon. Understanding the Ribbon is very important for us to use spring cloud, because load balancing is one of the most important means of high availability, ease of network stress, and capacity expansion of the system. In the example in the previous section, we implemented a declarative approach to load balancing. In fact, an internal call maintains a Resttemplate object that uses the Ribbon's automated configuration while enabling client load balancing through @loadbalanced. In fact, Resttemplate is the object that spring provides itself, not the new content. The reader does not know resttemplate can view the relevant documents.

Second, explore

We can start tracking from loadbalanced:

/** * Annotation to mark a resttemplate beans to being configured to use a loadbalancerclient * @author Spencer Gibb */@Target ({Elementtype.field, elementtype.parameter, Elementtype.method}) @Retention (retentionpolicy.runtime) @ Documented@inherited@qualifierpublic @interface loadbalanced {}

From its definition note for this annotation, we know that this annotation is used to mark Resttemplate to use a load-balanced client (loadbalancerclient) to configure Resttemplate. Then let's take a look at the Loadbalancerclient interface definition:

/** * Represents a client side load Balancer * @author Spencer Gibb */public interface Loadbalancerclient extends SERVICEI Nstancechooser {/** * Execute request using a serviceinstance from the loadbalancer for the specified * service * @param s Erviceid the service ID to look up the loadbalancer * @param request allows implementations to execute pre and post action S such as * incrementing metrics * @return The result of the Loadbalancerrequest callback on the selected * Serviceinstanc E */<t> T Execute (String serviceId, loadbalancerrequest<t> request) throws ioexception;/** * Execute request u Sing a serviceinstance from the loadbalancer for the specified * service * @param serviceId the service ID. LoadBalancer * @param serviceinstance the service to execute the request to * @param request allows implementations to EXE Cute pre and post actions such as * incrementing metrics * @return The result of the loadbalancerrequest callback on the S elected * ServiceinstancE */<t> T Execute (String serviceId, serviceinstance serviceinstance, loadbalancerrequest<t> request) throws ioexception;/** * Create A proper URI with a real host and port for systems to utilize.  * Some systems use a URI with the logical serivce name as the host, * such as Http://myservice/path/to/service. This would replace the * service name with the Host:port from the serviceinstance. * @param instance * @param original a URI with the host as a logical service name * @return a reconstructed URI */uri reco Nstructuri (serviceinstance instance, URI original);}

  

Loadbalancerclient is an integrated serviceinstancechooser, and then we look at the interface definition:
Public interface Serviceinstancechooser {    /**     * Choose a serviceinstance from the LoadBalancer for the specified s Ervice     * @param serviceId the service ID to look up the LoadBalancer     * @return A serviceinstance that matches the ServiceId     *    /Serviceinstance Choose (String serviceId);}

From the above annotations, we can know that the Choose () method chooses a corresponding service instance from the load balancer based on the incoming Serviceid service ID. The Execute () method executes the requested content based on the Serviceid service ID and request requests. The Reconstructuri () method constructs a suitable URI for the host:port. And ribbonloadbalancerclient is the concrete realization of loadbalancerclient.

We then look at the package where the loadbalancerclient is located, with the following structure:

we find that there is a class we need to focus on: loadbalancerautoconfiguration, from its source annotations we know is a configuration class for the Ribbon automation. The comments are as follows:

/** * Auto configuration for Ribbon (client side load balancing). * * @author Spencer Gibb * @author Dave Syer * @author'll Tran */@Configuration @conditionalonclass (resttemplate.class)/ /condition: Resttemplate must be in the project's Classpath @conditionalonbean (loadbalancerclient.class)/condition: The Spring container must contain the implementation of the Loadbalancerclient, That is ribbonloadbalancerclient@enableconfigurationproperties (loadbalancerretryproperties.class)//Start the retry function, Can Spring.cloud.loadbalancer.retry=false, cancel retry, default parameter is Truepublic class Loadbalancerautoconfiguration {@ Loadbalanced@autowired (required = false) Private list<resttemplate> resttemplates = Collections.emptylist (); Maintain a resttemplate list, annotated by loadbalanced. @Beanpublic Smartinitializingsingleton Loadbalancedresttemplateinitializer (//loading the restteplate of the initial session custom, Essentially initializes the Interceptinghttpaccessor specific call to final list<resttemplatecustomizer> customizers) {return new Smartinitializingsingleton () {@Overridepublic void aftersingletonsinstantiated () {for (Resttemplate resttemplate: Loadbalancerautoconfiguration.This.resttemplates) {for (Resttemplatecustomizer customizer:customizers) {customizer.customize (restTemplate);}}};} @Autowired (required = false) Private list<loadbalancerrequesttransformer> transformers = Collections.emptylist ( ); @Bean @conditionalonmissingbeanpublic loadbalancerrequestfactory loadbalancerrequestfactory (LoadBalancerClient Loadbalancerclient) {return new Loadbalancerrequestfactory (Loadbalancerclient, Transformers);} @Configuration @conditionalonmissingclass ("Org.springframework.retry.support.RetryTemplate") Static class loadbalancerinterceptorconfig {@Beanpublic loadbalancerinterceptor ribboninterceptor (loadbalancerclient Loadbalancerclient,loadbalancerrequestfactory requestfactory) {return new Loadbalancerinterceptor ( Loadbalancerclient, requestfactory);} @Bean @conditionalonmissingbeanpublic Resttemplatecustomizer Resttemplatecustomizer (Final LoadBalancerInterceptor Loadbalancerinterceptor) {return new Resttemplatecustomizer () {@Overridepublic void Customize (Resttemplate resttemplate) {list<clienthttprequestinterceptor> List = new Arraylist<> (Resttemplate.getinterceptors ( ); List.add (Loadbalancerinterceptor); resttemplate.setinterceptors (list);}};} @Configuration @conditionalonclass (retrytemplate.class) static class Retryautoconfiguration {@Beanpublic Retrytemplate retrytemplate () {retrytemplate template = new Retrytemplate (); Template.setthrowlastexceptiononexhausted (true); return template;} @Bean @conditionalonmissingbeanpublic loadbalancedretrypolicyfactory loadbalancedretrypolicyfactory () {return new Loadbalancedretrypolicyfactory.neverretryfactory ();} @Beanpublic retryloadbalancerinterceptor ribboninterceptor (loadbalancerclient loadbalancerclient, Loadbalancerretryproperties Properties,loadbalancedretrypolicyfactory Lbretrypolicyfactory, Loadbalancerrequestfactory requestfactory) {return new Retryloadbalancerinterceptor (Loadbalancerclient, Retrytemplate (), properties,lbretrypolicyfactory, requestfactory);} @Bean @conditionalonmissingbeanpublicResttemplatecustomizer Resttemplatecustomizer (//Custom resttemplate, essentially initializing interceptinghttpaccessorfinal Retryloadbalancerinterceptor loadbalancerinterceptor) {return new Resttemplatecustomizer () {@Overridepublic void Customize (resttemplate resttemplate) {list<clienthttprequestinterceptor> List = new Arraylist<> ( Resttemplate.getinterceptors ()); List.add (Loadbalancerinterceptor); resttemplate.setinterceptors (list);}}}

From the code above, we need to know about Loadbalancerinterceptor, which is used to intercept client-initiated requests to achieve client load balancing. In need of more chapters in order to clarify their relationship, I also have to read carefully, and so on reading is almost to tell you.

Third, the configuration

When the ribbon and Eureka are introduced into the spring cloud application, the automation configuration of the Ribbon implemented in Eureka is triggered.

The maintenance mechanism of serverlist is maintained by an instance of Discoveryenabledniwsserverlist, which gives the list of services to the Eureka Service governance mechanism for maintenance.

The implementation of Iping is maintained by an instance of niwsdiscoveryping, which also gives service checks to Eureka's service governance mechanism for maintenance.

By default, the Servicelist interface implementation used to get instance requests is in the domainextractingserverlist encapsulated in spring Cloud Eureka. Because Spring Cloud The Ribbon implements the region affinity policy by default, so we can implement the locale-based instance configuration scheme by Eureka the metadata configuration of the instance.

Like Eureka.instance.metadatamap.zone=hangzhou. Specify your region with the zone parameter.

In the spring cloud Ribbon and Spring Cloud Eureka Engineering, we can disable Eureka Maintenance implementations of the Ribbon service instances through parameter configuration.

Ribbon.eureka.enabled=false

Spring Cloud customer service side load Balancer 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.