Getting Started with SpringCloud - Ribbon Use

Spring Cloud Ribbon is a client-side load balancing tool based on HTTP and TCP, which is implemented based on Netflix Ribbon. Through the encapsulation of Spring Cloud, we can easily automatically convert service-oriented REST requests into client-side load balancing service calls. This article mainly introduces the basic use of Ribbon. The software versions used in this article are: Spring Boot 2.2.5.RELEASE, Spring Cloud Hoxton.SR3, Java 1.8.0_191.

1. Ribbon principle

Service List: Get a list of available services through the registry
Service filtering: filter the original service list using a certain policy, and return a valid server list for the client load balancer to use
Service heartbeat detection: used to detect whether a microservice instance is available; if a service instance is detected to be unavailable, it will be removed from the list in time
Load balancing strategy: select an effective service instance among multiple service instances and process corresponding service requests

2. Ribbon load balancing strategy

Strategy    name describe
RandomRule random strategy randomly select server
RoundRobinRule polling strategy Select server s in order (ribbon default policy)
RetryRule retry strategy During a configuration period, when the server selection is unsuccessful, it will always try to select an available server
BestAvailableRule Minimum Concurrency Policy Check the servers one by one, if the server circuit breaker is open, ignore it, and then select the server with the lowest concurrent link
AvailabilityFilteringRule Available filter policies Filter out servers that have been failing and are marked as circuit tripped, and filter out servers with high concurrent connections (active connections exceed the configured threshold)
ResponseTimeWeightedRule Response Time Weighted Weighting Policy The weight is assigned according to the response time of the server. The longer the response time, the lower the weight, and the lower the probability of being selected. The shorter the response time, the higher the weight, and the higher the probability of being selected. This strategy is very appropriate. It combines various factors, such as: network, disk, io, etc., which directly affect the response time.
ZoneAvoidanceRule area weighting strategy Comprehensively judge the performance of the region where the server is located, and the availability of the server, poll to select the server and determine whether the operating performance of an AWS Zone is available, and remove all servers in the unavailable Zone.

3. Use

3.1. Introducing dependencies

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

If eureka is used, robbin is included in eureka-client.

3.2. Define RestTemplate

package com.inspur.scdemo.client.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

3.3, call service

package com.inspur.scdemo.client.controller;

import com.inspur.scdemo.client.entity.CallResult;
import com.inspur.scdemo.client.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/getUser")
    public CallResult<User> getUser(long id) {
        logger.info(id + "");

        CallResult<User> result = null;
        try {
            //scdemo-server service name
            ResponseEntity<User> responseEntity = restTemplate.getForEntity("http://scdemo-server/getUser", User.class);
            result.setResult(responseEntity.getBody());
        } catch (Exception e) {
            result = new CallResult<User>(-1, "An exception occurs");
            e.printStackTrace();
        }
        return result;
    }
}

3.4. Description

Robbion load balancer is the default load balancer of spring Cloud, but it is currently under maintenance and is not recommended. Spring Cloud recommends using BlockingLoadBalancerClient as a load balancer; you can set spring.cloud.loadbalancer.ribbon.enabled to false to deactivate Robbion.

 

 

 

Tags: Spring Boot

Posted by MicahCarrick on Fri, 20 May 2022 15:51:02 +0300