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


边栏推荐
- 图解栈帧运行过程
- Where is win11 screen recording data saved? Win11 screen recording data storage location
- China bed and mattress market status research analysis and development prospect forecast report (2022)
- [动态规划]最长回文子串-对于动态转移循环顺序的思考
- What if win11 cannot delete the folder? Win11 cannot delete folder
- The difference between synchronize and volatile
- 目前期货怎么开户安全些?哪些期货公司靠谱些?
- Yyds dry goods inventory CEPH installation visual dashboard
- 数据治理,说起来容易,做起来难
- [dynamic programming] longest palindrome substring thinking about dynamic transfer cycle sequence
猜你喜欢
No nonsense, code practice will help you master strong caching and negotiation caching!
Créer le premier site Web avec idea
2022爱分析· IT运维厂商全景报告
NRM source switching tool
2022-2028 global iridium electrode industry research and trend analysis report
Interview shock 23: talk about thread life cycle and transformation process?
Nacos source code analysis 01 code structure
Where is win11 screen recording data saved? Win11 screen recording data storage location
Data governance is easier said than done
What are the debugging methods for nodejs
随机推荐
2022-2028 global co extrusion production line industry research and trend analysis report
Tlog helps Pangu framework realize microservice link log tracking
Research and Analysis on the current situation of China's magnetic detector Market and forecast report on its development prospect (2022)
Travel notes of 2022giao
Flutter 網絡請求封裝之Dio(Cookie管理、添加攔截器、下載文件、异常處理、取消請求等)
Where is win11 screen recording data saved? Win11 screen recording data storage location
Practice of product library platform nexus of Devops
Milan video technology exchange meeting sharing
Conglin environmental protection IPO meeting: annual profit of more than 200million to raise 2.03 billion
CVPR2022教程 | 马里兰大学《机器学习遥感处理:农业与粮食安全》教程
2022-2028 global vacuum jacket system industry survey and trend analysis report
Summary of basic knowledge of neural network
2022-2028 global variable frequency compressor technology industry research and trend analysis report
Mastering quantization technology is the key to video compression
Market depth analysis and development strategy consulting report of China's fire equipment market 2022-2028
Data governance is easier said than done
Data annotation in the second half: growth flywheel under PLG mode Manfu Technology
Open source optimized VVC encoder in general scenarios
Huasheng lithium battery IPO meeting: 9-month revenue of 690million; shenjinliang's family relationship is complex
Preliminary solution of i/o in socket programming