当前位置:网站首页>Ribbon core ⼼ source code analysis

Ribbon core ⼼ source code analysis

2022-06-25 22:44:00 enterpc

Catalog

One . Ribbon⼯ How it works

Two . @LoadBalanced Source analysis

​ ( One ) Research LoadBalancerAutoConfifiguration

( Two ) Analysis interceptor LoadBalancerInterceptor

1. concerns 1:

2. concerns 2: Choose services  

 3 . concerns 3:

( 3、 ... and )serverList analysis

3、 ... and . RoundRobinRule Polling strategy source code analysis

  Four . RandomRule Random strategy source code analysis


One . Ribbon⼯ How it works

  a key :Ribbon to restTemplate Added ⼀ An interceptor

reflection :Ribbon What are you doing? :
When we visit http://lagou-service-resume/resume/openstate/ When ,ribbon should
According to the service name lagou-service-resume Get the instance list of the service and follow ⼀ Fixed load balancing
The policy is obtained from the instance list ⼀ An example Server, And finally through RestTemplate Into the ⾏ Request access
Ribbon Detailed structure diagram ( Involving the bottom layer ⼀ Some components / Class description )
1) Get the list of service instances 2) Choose... From the list ⼀ individual server

Nucleus in Figure ⼼ yes Load Balancing Manager LoadBalancer( The overall coordinator , amount to ⼤ brain , To do things
love , Coordinate the limbs ), There are many around it IRuleIPing etc.
  • IRule: It is the load balancing policy object when selecting an instance
  • IPing: yes ⽤ To initiate... To the service ⼼ Jump detection , adopt ⼼ Jump detection to determine whether the service can ⽤
  • ServerListFilter: according to ⼀ Some rules filter and pass ⼊ List of service instances for
  • ServerListUpdater: Defined ⼀ A series of operations to update the service list

Two . @LoadBalanced Source analysis

We are RestTemplate Added... To the instance ⼀ individual @LoadBalanced annotation , Load sharing can be realized
equilibrium , Amazing , Let's next analyze the operation behind this annotation ( Load balancing process )
  • see @LoadBalanced annotation , Where is this annotation ⾥ What was recognized ?

  • LoadBalancerClient class ( Implementation class RibbonLoadBalancerClient, stay ⽤
package org.springframework.cloud.client.loadbalancer;

import org.springframework.cloud.client.ServiceInstance;

import java.io.IOException;
import java.net.URI;

/**
 * Represents a client-side load balancer.
 * @author Spencer Gibb
 */
public interface LoadBalancerClient extends ServiceInstanceChooser {

    //  According to service execution ⾏ Request content 
	<T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException;

    //  According to service execution ⾏ Request content 
	<T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request) throws IOException;

    //  Splicing request ⽅ type   In tradition ip:port  Now it's the service name :port  form 
	URI reconstructURI(ServiceInstance instance, URI original);
}
  • ⽼ The rules :SpringCloud Full benefit ⽤ 了 SpringBoot Of ⾃ Dynamic assembly features , look for spring.factories To configure ⽂ Pieces of

( One ) Research LoadBalancerAutoConfifiguration

 

 =========》》》LoadBalancerAutoConfifiguration⾥⾯ Content analysis of

The first ⼀ It's about : notes ⼊resttemplate Object to collection to be ⽤

  The first ⼆ It's about : notes ⼊resttemplate Customizer

  Third It's about : send ⽤ The customizer gives each in the collection ⼀ individual resttemplate Object to add ⼀ An interceptor

Here we are ⾥, We know ⽩, Annotated RestTemplate Object will be added ⼀ An interceptor
LoadBalancerInterceptor, This interceptor is used to intercept subsequent requests ⾏ Load handling .
therefore , Next ⼀ The next point is that we should analyze the interceptor LoadBalancerInterceptor------>>>intercept()
⽅ Law .

( Two ) Analysis interceptor LoadBalancerInterceptor

 ==========》》》》 analysis LoadBalancerInterceptor.intercept()⽅ Law

that ?RibbonLoadBalancerClient Where is the object ⾥ notes ⼊ Of ===》》 Go back to the original ⾃ Dynamic matching
Set class RibbonAutoConfifiguration in
The task of load balancing ⾏ It was handed over to what we first saw LoadBalancerClient Implementation class of interface :RibbonLoadBalancerClient Class object

⾮ Normal nucleus ⼼ Of ⼀ individual ⽅ Law :RibbonLoadBalancerClient.execute()

1. concerns 1:

 =====》》》 Return to the main configuration class RibbonAutoConfifiguration

 

 RibbonClientConfifiguration It is equipped with ⼤ Brain and limb ⼲

 

2. concerns 2: Choose services  

 ZoneAwareLoadBalancer#chooseServer

 ⽗ class :com.netflflix.loadbalancer.BaseLoadBalancer#chooseServer

Come to the of regional isolation strategy ⽗ class choose⽅ In law
com.netflflix.loadbalancer.PredicateBasedRule#choose

 

 3 . concerns 3:

As shown in the figure below RibbonLoadBalancerClient Class execute Methodical return Break the line of code , The consumer end Debug After operation , The browser requests the consumer , Enter the method

 

 

 AbstractClientHttpRequest#execute

here , It's already here RestTemplate The bottom layer holds ⾏ The code of , This will also validate the final request ⽤
It depends RestTemplate

( 3、 ... and )serverList analysis

Next , In into ⾏ load chooseServer When ,LoadBalancer Load balancer already has
serverList, So this serverList When was it noted ⼊ To LoadBalancer Medium , its ⼀ individual
Mechanism ⼤ What kind of ?
Came to RibbonClientConfifiguration

 

Still RibbonClientConfiguration There is one in this class ServerList<Server> Type of Bean 

  hold ⽬ Light is focused to make ⽤ This empty object ServerList Land ⽅

 

 

  Into the ⼊enableAndInitLearnNewServersFeature()⽅ Law

 

Get into ServerListUpdater Implementation class of interface EurekaNotificationServerListUpdater, Found in this class start(final UpdateAction updateAction) Method :

3、 ... and . RoundRobinRule Polling strategy source code analysis

/*
 *
 * Copyright 2013 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.netflix.loadbalancer;

import com.netflix.client.config.IClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * The most well known and basic load balancing strategy, i.e. Round Robin Rule.
 *
 * @author stonse
 * @author Nikos Michalakis <[email protected]>
 *
 */
public class RoundRobinRule extends AbstractLoadBalancerRule {

    private AtomicInteger nextServerCyclicCounter;
    private static final boolean AVAILABLE_ONLY_SERVERS = true;
    private static final boolean ALL_SERVERS = false;

    private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);

    public RoundRobinRule() {
        nextServerCyclicCounter = new AtomicInteger(0);
    }

    public RoundRobinRule(ILoadBalancer lb) {
        this();
        setLoadBalancer(lb);
    }

    //  Load balancing strategy class core ⼼⽅ Law 
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            log.warn("no load balancer");
            return null;
        }

        Server server = null;
        int count = 0;
        while (server == null && count++ < 10) {
            //  All available ⽤ List of service instances 
            List<Server> reachableServers = lb.getReachableServers();
            //  List of all service instances 
            List<Server> allServers = lb.getAllServers();
            int upCount = reachableServers.size();
            int serverCount = allServers.size();

            if ((upCount == 0) || (serverCount == 0)) {
                log.warn("No up servers available from load balancer: " + lb);
                return null;
            }
            //  get ⼀ A polling index 
            int nextServerIndex = incrementAndGetModulo(serverCount);
            //  Retrieve the service instance object according to the index 
            server = allServers.get(nextServerIndex);

            if (server == null) {
                /* Transient. */
                Thread.yield();
                continue;
            }
            //  Judge that the service can ⽤ After the return 

            if (server.isAlive() && (server.isReadyToServe())) {
                return (server);
            }

            // Next.
            server = null;
        }

        if (count >= 10) {
            log.warn("No available alive servers after 10 tries from load balancer: "
                    + lb);
        }
        return server;
    }

    /**
     * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
     *
     * @param modulo The modulo to bound the value of the counter.
     * @return The next value.
     */
    private int incrementAndGetModulo(int modulo) {
        for (;;) {
            //  Take out the last count 
            int current = nextServerCyclicCounter.get();
            //  Because it's polling , Count +1 Then take the mold of the total number 
            int next = (current + 1) % modulo;
            if (nextServerCyclicCounter.compareAndSet(current, next))
                return next;
        }
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}

  Four . RandomRule Random strategy source code analysis

原网站

版权声明
本文为[enterpc]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180948025707.html

随机推荐