当前位置:网站首页>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


边栏推荐
- be careful! This written examination method is gradually being replaced
- Talk about adapter mode
- This 110 year old "longevity" enterprise has been planning for the next century
- 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.)
- Global and Chinese oleic acid operation mode and market supply and demand forecast report 2022 ~ 2028
- 2022-2028 global industrial TFT LCD industry survey and trend analysis report
- [WPF] XAML code skills that can be directly used for converting CAD engineering drawings to WPF
- Research and Analysis on the current situation of Chinese acne drug market and forecast report on its development prospect (2022)
- Data annotation in the second half: growth flywheel under PLG mode Manfu Technology
- Market demand analysis and investment prospect research report of China's CNC machine tool industry 2022-2028
猜你喜欢

2022-2028 global industrial TFT LCD industry survey and trend analysis report

Nacos source code analysis 01 code structure

Jingwei Hengrun is registered through the science and Innovation Board: it plans to raise 5billion yuan, with a 9-month revenue of 2.1 billion yuan

简单好用的缓存库 gcache

聊聊Adapter模式

Win11 start menu right click blank? The right button of win11 start menu does not respond. Solution

Devops之制品库平台nexus实践

Programmer weekly (issue 4): the wealth view of programmers

How to design a complex business system? From the understanding of domain design, cloud native, micro service, and middle platform

Simple and easy-to-use cache library gcache
随机推荐
SSH modifies grub in heiqunhui ds918+ system 7.0.1 cfg
In depth analysis of Flink fine-grained resource management
Yyds dry goods inventory CEPH installation visual dashboard
Mastering quantization technology is the key to video compression
27 Chinese scholars including Yaoban and chendanqi from Tsinghua won the awards, and the list of winners of Sloan award in 2022 was issued
Zhihu Gaozan: what ability is important, but most people don't have it?
Exclusive interview with deepmindceo hassabis: we will see a new scientific Renaissance! AI's new achievements in nuclear fusion are officially announced today
NARI radar's IPO meeting: it plans to raise nearly 1billion yuan. Bao Xiaojun and his wife are Canadians
图解栈帧运行过程
Analysis report on market demand situation and investment direction of China's optical transmission equipment industry from 2022 to 2028
Milan video technology exchange meeting sharing
CVPR2022教程 | 马里兰大学《机器学习遥感处理:农业与粮食安全》教程
Pycharm 2022.1 EAP 2 release
Analysis of gpl3.0 license software copyright dispute cases
Summary of basic knowledge of neural network
Cvpr2022 tutorial | machine learning remote sensing processing: agriculture and food security, University of Maryland
Research on depth image compression in YUV420 color space
聊聊Adapter模式
Huasheng lithium battery IPO meeting: 9-month revenue of 690million; shenjinliang's family relationship is complex
How to design a complex business system? From the understanding of domain design, cloud native, micro service, and middle platform