[Source code comment] Ribbon's load balancing strategy and custom configuration and

Spring Cloud Ribbon's load balancing strategy and custom configuration

1. Ribbon is a 客户端load balancing tool based on HTTP and TCP . It is based on NetFlix Ribbon and can automatically convert service-oriented REST requests into client-side load balancing service calls.

2. Core components

com.netflix.loadbalancer.IRuleClass is the parent class of all load balancing strategies. Load balancing strategies are implemented based on its subclasses. The UML diagram is as follows:
Insert picture description here

3. Seven load balancing modes of ribbon

The default strategy is:RoundRobinRule(轮询策略)

Strategy mode Description
RetryRule Retry strategy: (First obtain the server according to the polling strategy, if the retrieval fails, keep retrying)
RandomRule Random strategy: (randomly select server)
RoundRobinRule ( 默认策略) Polling strategy: (choose server in turn)
BestAvailableRule Lowest concurrency strategy: (First filter out servers that are in the circuit breaker trip state due to multiple access failures, and then select a server with the least concurrency)
ZoneAvoidanceRule Regional trade-off strategy: (Compoundly judge the performance and availability of the area where the server is located, and then select the server)
AvailabilityFilteringRule Available filtering strategies: (First filter out servers that are in a circuit breaker trip state due to multiple access failures, as well as servers whose number of concurrent connections exceeds the threshold, and then poll the list of remaining servers)
ResponseTimeWeightedRule Response time weighting strategy: (weights are assigned according to response time. The longer the time, the lower the weight, 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 integrates the network , Disk, IO and other factors, these factors directly affect the response time of the server)

4. Custom load balancing strategy

Insert picture description here

Implement load balancing strategies through configuration classes

A:

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author layman
 * @description: 自定义ribbon的负载均衡配置类
 */
@Configuration
public class MyRule {
    
    
    @Bean
    public IRule myRule(){
    
    
        //切换为随机模式
        return new RandomRule();
    }
}

B:

Add annotations to the SpringBoot startup class

@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MyRule.class)
> // name:要访问的服务实例名
> // configuration:自定义额配置类

5. Ribbon's default strategy RoundRobinRule source code comment

Guess you like

Origin blog.csdn.net/single_0910/article/details/112686419