当前位置:网站首页>Ribbon core ⼼ source code analysis
Ribbon core ⼼ source code analysis
2022-06-25 22:44:00 【enterpc】
Catalog
Two . @LoadBalanced Source analysis
( One ) Research LoadBalancerAutoConfifiguration
( Two ) Analysis interceptor LoadBalancerInterceptor
2. concerns 2: Choose services
( 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

- 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
- 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 Customizer

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

( Two ) Analysis interceptor LoadBalancerInterceptor
==========》》》》 analysis LoadBalancerInterceptor.intercept()⽅ Law


⾮ 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




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

( 3、 ... and )serverList analysis

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


边栏推荐
- Use apiccloud AVM multi terminal component to quickly realize the search function in the app
- 2022-2028 global extrusion coating and lamination production line industry research and trend analysis report
- Simple and easy-to-use cache library gcache
- Sqlmap learning (sqli labs as an example)
- Illustration de l'exécution du cadre de pile
- Tiger Dao VC products are officially launched, a powerful supplement to seektiger ecology
- Reasons why MySQL cannot be connected externally after installing MySQL database on ECs and Solutions
- Research and Analysis on the current situation of China's magnetic detector Market and forecast report on its development prospect (2022)
- 聊聊Adapter模式
- Programmer weekly (issue 4): the wealth view of programmers
猜你喜欢

2022-2028 global horizontal reciprocating compressor industry research and trend analysis report
Pycharm 2022.1 EAP 2 release

记|一次exists关键字的学习记录

Tiger DAO VC产品正式上线,Seektiger生态的有力补充

Cvpr2022 tutorial | machine learning remote sensing processing: agriculture and food security, University of Maryland
Will neuvector be the next popular cloud native security artifact?

聊聊Adapter模式

2022-2028 global DC linear variable differential transformer (LVDT) industry survey and trend analysis report

Relinearization in homomorphic encryption (ckks)
Evaluate the generalization performance of models and build integrated models using out of pocket prediction (oof)
随机推荐
Evaluate the generalization performance of models and build integrated models using out of pocket prediction (oof)
[proteus simulation] Arduino uno pattern water lamp
Data governance is easier said than done
Dio encapsulé pour les requêtes réseau flutter (gestion des cookies, ajout d'intercepteurs, téléchargement de fichiers, gestion des exceptions, annulation des requêtes, etc.)
Data annotation in the second half: growth flywheel under PLG mode Manfu Technology
2022-2028 global selective laser sintering service industry research and trend analysis report
Analysis report on market demand situation and investment direction of China's optical transmission equipment industry from 2022 to 2028
Yyds dry goods inventory JD 2, why is redis so fast?
Open source optimized VVC encoder in general scenarios
Obsidian basic tutorial
2022-2028 global TFT touch screen industry research and trend analysis report
Where is win11 screen recording data saved? Win11 screen recording data storage location
[invitation letter] on March 4, the platform enabled digital intelligence Innovation -- UFIDA BiP PAAS cloud platform IUAP digital intelligence hundred cities forum · Jinan Station
Dialog+: Audio dialogue enhancement technology based on deep learning
Interview shock 23: talk about thread life cycle and transformation process?
华为云短信测了很多手机都提示发送频繁
2022爱分析· IT运维厂商全景报告
Preliminary solution of i/o in socket programming
Market depth analysis and development strategy consulting report of China's fire equipment market 2022-2028
Development trend of China's power carrier communication industry and Research Report on the 14th five year plan 2022 ~ 2028