Principle and Implementation of Spring Cloud server Load balancer Ribbon

Source: Internet
Author: User

Principle and Implementation of Spring Cloud server Load balancer Ribbon

Ribbon Introduction

In a distributed system, multiple instances are deployed for each microservice. How to evenly distribute service consumers to multiple service provider instances requires the use of Server Load balancer.

Ribbon is a Load balancer that provides many Load Balancing algorithms, such as polling and instant loading. After configuring the service provider address, Ribbon can evenly distribute service consumer requests.

Integrate Ribbon for service consumers

Add Ribbon dependency Library

<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-ribbobn</artifactId></dependency>

Add @ LoadBalaced annotation to RestTemplate to integrate RestTemplate and Ribbon.

@Bean@LoadBalancedpublic RestTemplate restTemplate(){  return new RestTemplate();}

Modify the Controller and request address to http: // flim-user/. When Ribbon and Eureka are used in combination, the virtual host name is automatically mapped to the network address of the microservice, loadBalancerClient is injected to output the selected microservice node.

@RestControllerpublic class MovieController {  private final Logger log = LoggerFactory.getLogger(MovieController.class);  @Autowired  private RestTemplate restTemplate;  @Autowired  private LoadBalancerClient loadBalancerClient;  @GetMapping("/user/{id}")  public User findById(@PathVariable int id){    return this.restTemplate.getForObject("http://flim-user/"+id,User.class);  }  @GetMapping("/log-instance")  public void logInstance(){    ServiceInstance serviceInstance = this.loadBalancerClient.choose("flim-user");    log.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());  }}

Run the test program

  1. Start Eureka Server
  2. Start two or more flim-user instances
  3. Start flim-consumer
  4. Access http: // localhost: 8761/to check whether the microservice flim-user is successfully registered.
  5. Multiple accesses to http: // localhost: 8010/user/1 will return the following results

{"Id": 1, "username": "account1", "name": "Zhang San", "age": 20, "balance": 100.00}

Multiple accesses to the http: // localhost: 8010/log-instance console will output the following information:

The requests are evenly distributed to two user microservices.

20:47:53. 975 INFO 12313 --- [nio-8010-exec-2] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8764
20:47:54. 215 INFO 12313 --- [nio-8010-exec-1] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8763
20:47:54. 445 INFO 12313 --- [nio-8010-exec-3] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8764
20:47:54. 690 INFO 12313 --- [nio-8010-exec-4] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8763
20:47:54. 935 INFO 12313 --- [nio-8010-exec-5] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8764

Note: you cannot set restTemplate. getForObject (...) and loadBalancerClient. choose (...) written in the same method, because rest-Template is actually a Ribbon client, it already contains "choose" behavior

Configure Ribbon in code mode

You can use Java code or attributes to customize Ribbon configurations. The default configuration class of Ribbon is RibbonClientConfiguration. You can also use a POJO to customize Ribbon configurations. This configuration is fine-grained, different Ribbon clients can use different configurations.

Create Ribbon configuration class

/*** The configuration class * should not be scanned by ComponentScan */@ Configurationpublic class RibbonConfiguration {@ Bean public IRule ribbonRule () {// Configure the server Load balancer rules, change to random return new RandomRule ();}}

Use the @ RibbonClient or @ RibbonClients annotation to specify the configuration class for the service provider

@SpringBootApplication@EnableDiscoveryClient@RibbonClient(name = "flim-user",configuration = RibbonConfiguration.class)public class FlimConsumerApplication {  @Bean  @LoadBalanced  public RestTemplate restTemplate(){    return new RestTemplate();  }  public static void main(String[] args) {    SpringApplication.run(FlimConsumerApplication.class, args);  }}

Access test URL http: // localhost: 8010/log-instance. The requests are randomly distributed to the two microservices.

21:08:52. 769 INFO 12524 --- [nio-8010-exec-7] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8763
21:08:52. 946 INFO 12524 --- [nio-8010-exec-8] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8763
21:08:53. 138 INFO 12524 --- [nio-8010-exec-9] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8763
21:08:53. 319 INFO 12524 --- [io-8010-exec-10] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8764
21:08:53. 511 INFO 12524 --- [nio-8010-exec-1] com. linyuan. controller. MovieController: flim-user: linyuandembp: 8763

Note: The RibbonConfiguration class cannot be scanned by @ ComponentScan. Otherwise, the configuration information will be shared by all @ ribbonclients. Therefore, if you only want to customize the configuration of a Ribbon client, you must prevent scanning by @ ComponentScan.

Configure Ribbon in the configuration file

You can use the configuration file to customize the Ribbon attribute. The prefix is <clientName>. ribbon.

  1. NFLoadBalancerClassName: configure the ILoadBalancer implementation class
  2. NFLoadBalancerRuleClassName: The Implementation class for configuring IRule
  3. NFLoadBalancerPingClassName: Configure IPing implementation class
  4. NIWSServerListClassName: ServerList implementation class
  5. NIWSServerListFilterClassName: The Implementation class for configuring ServerListFilter

Use the configuration file to define the Ribbon Configuration

flim-user: ribbon:  NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

Common global Ribbon configurations

Ribbon: ConnectionTimeout: # connection timeout ReadTimeout: # Read timeout OkToRetryOnAllOperatotions: # retry MaxAutoRetriesNextServer for all operation requests: # Switch the number of server instance retries MaxAutoRetries: # Number of Retries on the current instance ServerListRefreshInterval: # interval between refreshing the service list source

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.