Ribbon load balancing of spring cloud Alibaba project

Posted by Love_Daddy on Mon, 27 Dec 2021 02:55:21 +0100

SpringCloudAlibaba essay directory

I SpringCloudAlibaba is the father of the project

II Nacos building and service registration of spring cloud Alibaba project

III Producers and consumers of spring cloud Alibaba project

IV Ribbon load balancing of spring cloud Alibaba project

V OpenFeign remote call of spring cloudalibaba project

Vi Nacos config configuration center of spring cloud Alibaba project

VII

8, Seata distributed transaction of spring cloud Alibaba project

9, GateWay gateway of spring cloudalibaba project

10, SkyWalking link tracking of spring cloud Alibaba project

 

Ribbon load balancing of spring cloud Alibaba project

1. Introduction to Ribbon

Spring Cloud Ribbon is a Netflix open source software tool for client load balancing. It supports the communication of each client in the cluster, helps to control the behavior of HTTP and TCP clients, and provides many load balancing algorithms, such as polling, on-demand, etc. at the same time, it can also implement custom algorithms.

In the microservices built by Spring Cloud, Ribbon, as a load balancer for service consumers, can be used in two ways: one is combined with RestTemplate, and the other is combined with feign (now closed source and not updated, replaced by OpenFeign officially provided by Spring Cloud, and the enhanced version of feign). Feign has integrated Ribbon by default.

Ribbon is an open source project released by Netflix. Its main function is to provide complex equalization algorithms and service calls on the client.

Ribbon client component provides a series of complete configuration items, such as timeout, Retry, etc.

Ribbon will automatically help you link these machines based on certain rules (such as simple polling, random links, etc.).

2. Ribbon local load balancing client VS Nginx server load balancing difference

Nginx is server load balancing. All client requests will be handed over to nginx, and then nginx forwards the requests. That is, load balancing is realized by the server.

Ribbon local load balancing (or service consumer), when calling the micro service interface, will obtain the registration information service list in the registry and cache it to the JVM local, so as to realize the RPC remote service call technology locally.

3. ribbon and LoadBalance

ribbon status: stop and change dimension

Alternative - Spring Cloud Loadbalancer

a. ribbon and loadbalancer are load balancing components of spring cloud
b. ribbon is a Netflix open source load balancing component based on HTTP, TCP and other protocols. The loadBalancer is written by SpringCloud itself and obtains the rpc address of the load balancer according to the service id.
c. the ribbon needs to manually call the target service in the code. The underlying principle of loadBalancer is to call the ribbon by default to achieve client load balancing
The ribbon will not be maintained since May 2019. In the later stage, the loadbalancer will become the mainstream. At present, the ribbon is still used more. Loadbalancer supports ribbon.

LoadBalance and ribbon comparison:

Load balancing comparison

The ribbon provides the default load balancing policy in 7. Common load balancing policies are covered. Generally, we use "ZoneAvoidanceRule" to judge the performance of the server area and the availability of the server, and select the server

Configuration richness

  • Currently, spring cloud loadbalancer {only supports the configuration of retry operation

  • ribbon supports timeout, lazy load processing, retry and its integration with hystrix advanced properties

There are only a few load balancing strategies. The ribbon has been quite rich. It doesn't matter if the source is closed and not updated. These are enough. At present, the ribbon is honest and practical. We will consider replacing it later when LoadBalance is really powerful.
4. Modify default load balancing
Method 1: configuration class
 
RibbonRuleConfig, load balancing configuration class
/**
 * Method 1: configure load balancing policy
 * RibbonRuleConfig It cannot be scanned by @ ComponentScan of @ SpringBootApplication, otherwise it is the effect of global configuration
 */
@Configuration
public class RibbonRuleConfig {
    /**
     * Global configuration, specifying load balancing policy
     * @return
     */
    @Bean
    public IRule iRule(){//The method name must be iRule,Compliance is greater than configuration
        return new RandomRule();//Using random load balancing strategy
        //return new NacosRule();//Specify use Nacos Load balancing strategy provided (give priority to calling instances of the unified cluster based on random weight)
    }
}

Startup class:

@SpringBootApplication
@EnableDiscoveryClient//Can add or not, depending on the version, from Spring Cloud Edgware Start,@EnableDiscoveryClient Can be omitted. Just add relevant dependencies and configure them accordingly to register the microservice to the service discovery component.
//Multiple can be configured  RibbonRuleConfig Cannot be@SpringBootApplication of@ComponentScan Scan to, so put it to the next level, otherwise it will be the effect of global configuration
@RibbonClients(value = {
        @RibbonClient(name = "service-stock",configuration = RibbonRuleConfig.class)
})
public class ServiceOrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceOrderApplication.class, args);
    }
}

Method 2: configuration file

application.properties

# apply name
spring.application.name=service-order
# Application service WEB access port
server.port=8040
# Nacos help document: https://nacos.io/zh-cn/docs/concepts.html
# Nacos certification information
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# Nacos service discovery and registration configuration, where the sub attribute is server-addr appoint Nacos Server host and port
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# Register with the specified namespace of nacos. The default is public
spring.cloud.nacos.discovery.namespace=public

#Mode 2: load balancing profile
#Specify to use the load balancing policy provided by Nacos (call the same cluster instance first, based on random and weight)
service-stock.ribbon.NFLoadBalancerRuleClassName=com.alibaba.cloud.nacos.ribbon.NacosRule

5. Custom load balancing policy

Modify method 2. Do not use the official load balancing policy, and customize the load balancing configuration file

Custom load balancing policy rule CustomRule class:

/**
 * Method 2: Customize load balancing policy rules
 */
public class CustomRule extends AbstractLoadBalancerRule {

    /**
     * Initialize configuration information
     * @param iClientConfig
     */
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) { }

    /**
     * Load balancing policy rules. Take random numbers as an example here. You can write other rules or create new rules yourself
     * @param o
     * @return
     */
    @Override
    public Server choose(Object o) {
        ILoadBalancer  iLoadBalancer = this.getLoadBalancer();
        //Gets the currently requested service instance
        List<Server> reachableServers = iLoadBalancer.getReachableServers();
        //Generate random numbers based on service instances
        int random = ThreadLocalRandom.current().nextInt(reachableServers.size());
        //Get the service under this random number
        Server server = reachableServers.get(random);
        return server;
    }
}

application.properties

# apply name
spring.application.name=service-order
# Application service WEB access port
server.port=8040
# Nacos help document: https://nacos.io/zh-cn/docs/concepts.html
# Nacos certification information
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# Nacos service discovery and registration configuration, where the sub attribute is server-addr appoint Nacos Server host and port
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# Register with the specified namespace of nacos. The default is public
spring.cloud.nacos.discovery.namespace=public

#Mode 2: load balancing profile
#Specify to use the load balancing policy provided by Nacos (call the same cluster instance first, based on random and weight)
#service-stock.ribbon.NFLoadBalancerRuleClassName=com.alibaba.cloud.nacos.ribbon.NacosRule
#Specify custom load balancing policy rule CustomRule class and use self-defined rules
service-stock.ribbon.NFLoadBalancerRuleClassName=com.qt.ribbon.rule.CustomRule

6. Replace the Ribbon with LoadBalancer

Currently, LoadBalancer only provides polling load policy.

Remove ribbon from nacos

Method 1, modify POM XML (recommended to prevent duplicate names of some classes):

<!-- nacos Service registration discovery (client) dependency -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <!--remove ribbon support-->
    <exclusions>
        <exclusion>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Method 2: modify the configuration file application properties:

# apply name
spring.application.name=service-order
# Application service WEB access port
server.port=8040
# Nacos help documentation: https://nacos.io/zh-cn/docs/concepts.html
# Nacos certification information
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# Nacos service discovery and registration configuration, where the sub attribute server addr specifies the Nacos server host and port
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# Register with the specified namespace of nacos. The default is public
spring.cloud.nacos.discovery.namespace=public

#Do not use ribbon
spring.cloud.loadbalancer.ribbon.enabled=false

Add loadbalancer dependency

<!-- add to loadbalancer rely on-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

RestTemplateConfig class

/**
 * SpringBoot-RestTemplate Implementation calls third-party API s
 */
@Configuration
@Component
public class RestTemplateConfig {
    @Bean
    @LoadBalanced //Enable load balancing so that RestTemplate Request support for load balancing
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        RestTemplate restTemplate = builder.build();
        return restTemplate;
    }
}

Access address: http://localhost:8040/order/addOrder

Topics: Load Balance Spring Cloud ribbon springcloudalibaba