springcloud-04-Customizing how the Ribbon is configured

Source: Internet
Author: User

In the Dubbo project, zookeeper is the registry that helps us to achieve scheduling and load balancing capabilities, known as server-side load balancing, Springcloud, and client load balancing with Ribben implementation

What is the ribbon?

The Ribbon is an open source project for cloud mid-tier services from Netflix, and its main function is to provide client side load balancing algorithms. The Ribbon client component provides a complete set of configuration items such as connection timeouts, retries, and so on. Simply put, the Ribbon is a client load balancer, and we can list all the machines behind the load balancer in the configuration file, and the Ribbon will automatically help you to connect these machines based on some sort of rule (such as simple polling, random connections, etc.). It is also easy to implement a custom load balancing algorithm using the Ribbon.

Eureka using the approximate architecture of the Ribbon

Ribbon work is divided into two steps: The first step is to select the Eureka server, which is preferred in the same zone and less load server; the second step is to select an address in the list of service registrations from the Server, based on the user-specified policy. The Ribbon provides a variety of strategies, such as polling round robin, stochastic random, weighted by response time, and so on.

Implemented by code:

Transform a cosumer-movie into a ribbon project

Add an annotation class that needs to be placed under a package not scanned by the MainClass, or filtered through @componentscan in the MainClass

The annotation filter is used here, so we need an annotation first:

Package com.wenbronk.cosumer.ribben.annotation; /*  * /public @interface excudeannotation {}

Then there is a ribbon annotation declaration class:

Package Com.wenbronk.cosumer.ribben.config;import Com.netflix.loadbalancer.irule;import Com.netflix.loadbalancer.randomrule;import Com.wenbronk.cosumer.ribben.annotation.excudeannotation;import Org.springframework.context.annotation.bean;import org.springframework.context.annotation.Configuration;/** * The default rule is polling, this is a random rule * The class must be placed under a package that cannot be scanned, or add exclusions, although he must have annotations * Created by Wenbronk on 2017/5/18.*/@Configuration @excudeannotation Public classMyribbonconfig {@Bean PublicIRule Ribbonrule () {return NewRandomrule (); }}

Filtering in the MainClass

Package Com.wenbronk.cosumer.ribben;import Com.wenbronk.cosumer.ribben.annotation.excudeannotation;import Com.wenbronk.cosumer.ribben.config.myribbonconfig;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.cloud.client.loadbalancer.loadbalanced;import Org.springframework.cloud.netflix.eureka.enableeurekaclient;import Org.springframework.cloud.netflix.ribbon.ribbonclient;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.componentscan;import Org.springframework.context.annotation.FilterType; Import org.springframework.web.client.RestTemplate;/** * ribbonclient Custom Ribbon Client * Created by Root on 2017/5/18.*/@SpringBootApplication @enableeurekaclient//Use this rule to not be placed under a scanned path, if you want to place it, you need to add custom annotations@RibbonClient (name ="Microserver-provider-user", configuration = Myribbonconfig.class) @ComponentScan (excludefilters= {@ComponentScan. Filter (type = filtertype.annotation, value = {excudeannotation).class})}) Public classmovieribbenapplication {/** * use loadbalanced to turn on client load Balancing function * @return*/@Bean @LoadBalanced Publicresttemplate resttemplate () {return Newresttemplate (); }     Public Static voidMain (string[] args) {Springapplication.run (movieribbenapplication.class, args); }}
Verify:

By configuring the port, start the User Service 4 instances and register as 2 services, add the following code to the controller of the Movie-ribbon

Package Com.wenbronk.cosumer.ribben.controller;import Com.wenbronk.cosumer.ribben.entity.user;import Org.springframework.beans.factory.annotation.autowired;import org.springframework.cloud.client.ServiceInstance; Import Org.springframework.cloud.client.loadbalancer.loadbalancerclient;import Org.springframework.web.bind.annotation.getmapping;import org.springframework.web.bind.annotation.PathVariable; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import org.springframework.web.client.RestTemplate;/** * Created by Root on 2017/5/18.*/@RestController Public classMovieribbencontroller {@AutowiredPrivateresttemplate resttemplate; @AutowiredPrivateloadbalancerclient loadbalancerclient; @RequestMapping ("/movie/{id}")     PublicUser FindByID (@PathVariable Long id) {returnResttemplate.getforobject ("http://microservice-provider-user/simple/"+ ID, User.class); } @GetMapping ("/test")     Public voidTest () {Serviceinstance instance= This. Loadbalancerclient.choose ("Microservice-provider-user"); System. out. println ("111:"+ Instance.getserviceid () +": "+ instance.gethost () +": "+Instance.getport ());//System.out.println (instance.tostring ());serviceinstance Instance1= This. Loadbalancerclient.choose ("microservice-provider-user-1"); System. out. println ("222:"+ Instance1.getserviceid () +": "+ instance1.gethost () +": "+Instance1.getport ());//System.out.println (Instance1);//System.out.println (Instance = = Instance1);    }}

By repeatedly sending requests through the browser, you can see in the console that only Provide-user uses our custom rules, User-1 still uses the Ribbon's default rule polling

Customize the ribbonclient by configuring the file:

starting with version 1.2.0, Spring Cloud Netflix now supports the use of attributes and Ribbon documentation is compatible from Defining Ribbon Clients .

Configuration priority: Config file > Java code > Springcloud Default

Configuration file configuration, just add the following in Yml '
Users:  Ribbon:    NFLoadBalancerRuleClassName:com.netflix.loadbalancer.WeightedResponseTimeRule
Nfloadbalancerruleclassname is the rule, in addition to this rule springcloud there are
There are also many classes that can be added for each rule

Mainclass.java
Package Com.wenbronk.cosumer.ribbon.yml;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.cloud.netflix.eureka.enableeurekaclient;import Org.springframework.context.annotation.Bean; Import org.springframework.web.client.RestTemplate;/** * Created by Wenbronk on 2017/5/20.*/@SpringBootApplication @enableeurekaclient Public classMoveiribbonymlapplicatoin {@Bean Publicresttemplate resttemplate () {return Newresttemplate (); }     Public Static voidMain (string[] args) {Springapplication.run (moveiribbonymlapplicatoin.class, args); }}

Movieribboncontroller

Package Com.wenbronk.cosumer.ribbon.yml.controller;import Com.wenbronk.cosumer.ribbon.yml.entity.user;import Org.springframework.beans.factory.annotation.autowired;import org.springframework.cloud.client.ServiceInstance; Import Org.springframework.cloud.client.loadbalancer.loadbalancerclient;import Org.springframework.web.bind.annotation.getmapping;import org.springframework.web.bind.annotation.PathVariable; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import org.springframework.web.client.resttemplate;/** * Created by Root on 2017/5/18.    */@RestControllerpublic class Movieribbencontroller {@Autowired private resttemplate resttemplate;    @Autowired private loadbalancerclient loadbalancerclient; @RequestMapping ("/movie/{id}") Public User FindByID (@PathVariable Long ID) {return resttemplate.getforobject ("H    ttp://microservice-provider-user/simple/"+ ID, user.class); } @GetMapping ("/tEST ") public void Test () {Serviceinstance instance = this.loadBalancerClient.choose (" Microservice-provider-user        "); System.out.println ("111:" + instance.getserviceid () + ":" + instance.gethost () + ":" + instance.getport ());//Sy        Stem.out.println (Instance.tostring ());        Serviceinstance Instance1 = This.loadBalancerClient.choose ("microservice-provider-user-1");        System.out.println ("222:" + instance1.getserviceid () + ":" + instance1.gethost () + ":" + instance1.getport ());//    System.out.println (Instance1);//System.out.println (instance = = Instance1); }}

  

springcloud-04-Customizing how the Ribbon is configured

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.