Spring cloud (Part 006) movie microservice, load balancing on the client side with ribbon


Spring cloud (Part 006) movie microservice, load balancing on the client side with ribbon

1、 General introduction

1. Ribbon is an open source project of cloud middle tier service released by Netflix. Its main function is to provide client load balancing algorithm.
2. The ribbon client component provides a series of perfect configuration items, such as connection timeout, Retry, etc. In short, ribbon is a client-side load balancer. We can list all the machines behind the load balancer in the configuration file. Ribbon will automatically help you connect these machines based on some rules (such as simple polling, random connection, etc.), and we are also easy to use ribbon to implement a custom load balancing algorithm.
3. Ribbon implements soft load balancing with three core points:
   *Service discovery, finding the list of dependent services
   *Service selection rules, how to select an effective service among multiple services
   *Service monitoring, detection of invalid services, efficient elimination of invalid services

4. This chapter is just a simple use of ribbon to achieve client load balancing and select the back-end micro service list. If you have a deeper understanding of the use of ribbon, please continue to look forward to the next chapter on ribbon.

2、 Implementation steps

2.1 add Maven reference package

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

        <! -- web module -- >

        <! -- client discovery module -- >

        <! -- module to monitor and manage production environment -- >


2.2 add application configuration file (springms consumer movie ribbonsrcmainresources application. YML)

    name: springms-consumer-movie-ribbon
  port: 8010
#When doing load balancing, you do not need this dynamically configured address
#  userServicePath: http://localhost:7900/simple/
#    healthcheck:
#      enabled: true
      defaultZone: http://admin:[email protected]:8761/eureka
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}

2.3 add entity user class (springms consumer movie ribbonsrcmainjavacomspringmscloudentityuser. Java)

package com.springms.cloud.entity;

import java.math.BigDecimal;

public class User {

    private Long id;

    private String username;

    private String name;

    private Short age;

    private BigDecimal balance;

    public Long getId() {
        return this.id;

    public void setId(Long id) {
        this.id = id;

    public String getUsername() {
        return this.username;

    public void setUsername(String username) {
        this.username = username;

    public String getName() {
        return this.name;

    public void setName(String name) {
        this.name = name;

    public Short getAge() {
        return this.age;

    public void setAge(Short age) {
        this.age = age;

    public BigDecimal getBalance() {
        return this.balance;

    public void setBalance(BigDecimal balance) {
        this.balance = balance;


2.4 add the movie web access layer controller (springms consumer movie ribbonsrcmainjavacomspringmscloudcontrollermovieribboncontroller. Java)

package com.springms.cloud.controller;

import com.springms.cloud.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

 *In the web control layer of the movie microservice ribbon, the resttemplate annotated with loadbalanced is used to load balance and schedule different back-end microservices;
 * @author hmilyylimh
 * @version 0.0.1
 * @date 2017/9/17
public class MovieRibbonController {

    private RestTemplate restTemplate;

    public User findById(@PathVariable Long id) {
        // http://localhost:7900/simple/
        // VIP:virtual IP
        // HAProxy Heartbeat

        return this.restTemplate.getForObject("http://springms-provider-user/simple/" + id, User.class);

     *Add the code for testing the spring MS sidecar microservice.
     * @return
    public String sidecar() {
        return this.restTemplate.getForObject("http://springms-sidecar/", String.class);

     *Add the code for testing the spring MS sidecar microservice.
     * @return
    public String sidecarHealth() {
        return this.restTemplate.getForObject("http://springms-sidecar/health.json", String.class);

2.5 add the movie microservice startup class (springms consumer movie ribbonsrcmainjavacomspringmscloud msconsumermovierribbonapplication. Java)

package com.springms.cloud;

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.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

 *Movie microservice uses ribbon to balance the load on the client.
 *Loadbalanced: this load balancing annotation has integrated the ribbon;
 *After entering the address of http: // localhost: 8010 / movie / 3 in the browser, note that loadbalanced will perform load balancing and allocate the request to different [user microservices];
 *The default load balancing algorithm of ribbon is: polling;
 * @author hmilyylimh
 * @version 0.0.1
 * @date 2017/9/17
public class MsConsumerMovieRibbonApplication {

    public RestTemplate restTemplate(){
        return new RestTemplate();

    public static void main(String[] args) {
        SpringApplication.run(MsConsumerMovieRibbonApplication.class, args);
        System. Out. Println ("[[[[[[movie micro Service Ribbon]]]] has been started.");

3、 Ribbon brief process analysis

Ribbon's load balancing is mainly implemented by loadbalancerclient, which is specifically handled by iloadbalancer,
 Iload balancer obtains the registration list information from eurekaclient by configuring iRule, iping and other information, and sends "Ping" to eurekaclient once in 10 seconds by default,
 Then check whether to update the service list. Finally, after getting the registration list, Iload balancer performs load balancing according to iRule's policy.

 After the resttemplate is annotated by @ loadbalance, it can be used for load balancing. It mainly maintains a list of resttemplates annotated by @ loadbalance, adds interceptors to the list of resttemplates, and then submits them to the load balancer for processing.

Four, test

 1、 Movie microservice, load balancing on the client side with ribbon:

 1. Start the spring MS discovery Eureka module service, and start one port;
 2. Start the spring MS provider user module service, start three ports (7900, 7899, 7898);
 3. Start the spring MS consumer movie ribbon module service, and start 1 port;
 4. Enter the address http: // localhost: 7900 / simple / 1 in the browser to see that the information is printed successfully, indicating that the user's microservice is normal;
 5. Enter the address http: // localhost: 8761 in the browser and enter the user name and password admin / admin to enter Eureka microservice and display it in the web page, and verify that the three user microservices and 1 movie ribbon microservice are indeed registered in Eureka service;

 6. Enter the address http: // localhost: 8010 / movie / 1 in the browser for 6 consecutive times;
 7. Then run to the three servers of the user microservice to check the SQL logs of Hibernate query users. Each user microservice is called twice evenly;

 Conclusion: it can be seen that three user microservices are started to register in Eureka service center, and then the film microservices are scheduled to load balance on the client side through the ribbon, thus realizing the load balance algorithm on the client side. The default scheduling algorithm is polling;

5、 Download address


Spring cloudtutorial communication QQ group: 235322432

Spring cloudtutorial communication wechat group: wechat communication group QR code image link

Welcome to pay attention, your affirmation is the biggest support to me!!!

Recommended Today

PHP realizes UnionPay business H5 payment

UnionPay business H5 payment interface document: document address 1: H5 payment interface address: 1: Alipay payment Test address: Official address: https://api-mop.chinaums.com/ 2: UnionPay payment Test address: Official address: https://api-mop.chinaums.com/ 2: Basic parameters required by the interface The interface uses get parameters. After the interface parameters are directly put into the interface address, the […]