当前位置:网站首页>Ribbon's loadbalancerclient, zoneawareloadbalancer and zoneavoidancerule are three musketeers by default
Ribbon's loadbalancerclient, zoneawareloadbalancer and zoneavoidancerule are three musketeers by default
2022-07-24 09:58:00 【Happy Valley melodious】
1.RibbonLoadBalancerClient From above
stay ribbon in LoadBalanceClient There is only one subclass , This subclass is RibbonLoadBalancerClient. It is from LoadBalancerInterceptor Accept the request , Enter the real load balancing process .![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-BnU5dnzx-1623398061677)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/5b961a52-9c29-48b6-8c00-bcd7a4c31316/Untitled.png)]](/img/5a/ea677a4b85b214b7dcc0938c769a07.png)
2.RibbonLoadBalancerClient What did you do ?
- Get load balancer
ILoadBalancer - Select services according to load balancer and rules (
chooseServer) - Record each serviceId The state of
RibbonStatsRecorder - perform request Request and return the result
T returnVal = request.apply(serviceInstance);
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-8kTVlXnc-1623398061685)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ef575409-0135-44a7-86c0-6223a55a119d/Untitled.png)]](/img/08/c40db2d5df7b3cae91785f16850843.png)
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-ROpARyHN-1623398061686)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1905e091-527a-4103-a3f1-eb73892a95a7/Untitled.png)]](/img/87/03459353fa4f5f2d8bd4dbc6e6916e.png)
3. Get load balancer getLoadBalancer(serviceId)
Here we see through serviceId Obtain the load balancer , That means every service ( Contains multiple service instances ) You should have your own load balancer , There should be some mechanisms to maintain the list of services , There are corresponding load balancing strategies , And the data maintenance required by the load balancing strategy .
adopt debug, I found it through AnnotationConfigApplicationContext For maintenance. , Then from the inside according to service Type to get the corresponding instance information .
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-uQqAsGOh-1623398061689)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/2a7aaf24-7c44-463d-b993-dcd8c52da688/Untitled.png)]](/img/45/f3c37ca01668d3a42150ff36e39f12.png)
See here that the default load balancer is ZoneAwareLoadBalancer
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-blwuvhR7-1623398061692)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/5df29129-fb27-41a3-9b80-83a683c4e989/Untitled.png)]](/img/e5/42b8ab5cb7f1d7d07930308a22a56b.png)
Where is the load balancer initialized ? I will write a separate article on this later , I'll skip here first .
4.ZoneAwareLoadBalancer How to choose services
public Server chooseServer(Object key) {
// We know that every service has a load balancer , Here is the load balancing statistic for each service
// See how many requests load balancing has been done
if (counter == null) {
counter = createCounter();
}
counter.increment();
if (rule == null) {
return null;
} else {
try {
// EH , Here comes the rule selection
return rule.choose(key);
} catch (Exception e) {
logger.warn("LoadBalancer [{}]: Error choosing server for key {}", name, key, e);
return null;
}
}
}
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-iZ2ONgg6-1623398061693)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/79c1399d-122f-4f41-b7cd-1b334aab8c50/Untitled.png)]](/img/0d/814651bc293a1885e99b18f9c05616.png)
Here we can see that the default load balancing policy is ZoneAvoidanceRule
5.ZoneAvoidanceRule How to choose services ?
public Server choose(Object key) {
ILoadBalancer lb = getLoadBalancer();
// This completes the selection of services
// And we can see , there lb.getAllServers explain ILoadBalancer Directly or indirectly stores the service list
Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key);
if (server.isPresent()) {
return server.get();
} else {
return null;
}
}
You can see from above chooseRoundRobinAfterFiltering This method means after filtering , Select the load balancing method of polling .
and lb.getAllServers Is to get all service instances of this service .
thus it can be seen chooseRoundRobinAfterFiltering Is the key point of choice .
public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers, Object loadBalancerKey) {
// Filter out service instances without composite conditions
List<Server> eligible = getEligibleServers(servers, loadBalancerKey);
if (eligible.size() == 0) {
return Optional.absent();
}
// incrementAndGetModulo This is the key calculation of polling
return Optional.of(eligible.get(incrementAndGetModulo(eligible.size())));
}
The calculation process is relatively simple
// This is the next time the current rule is stored
private final AtomicInteger nextIndex = new AtomicInteger();
private int incrementAndGetModulo(int modulo) {
for (;;) {
int current = nextIndex.get();
// modulus
int next = (current + 1) % modulo;
// Reset next The pointer
if (nextIndex.compareAndSet(current, next) && current < modulo)
return current;
}
}
In fact, the load balancing of polling mode is in n Servers are accessed in order , By taking a mold nextIndex Never greater than modulo The situation of .
Here, choose which service instance to use Server after , How to link ServiceProvider Replace the service name with Server Medium ip And ports ?
6. Service name to ip+ Port procedure
1. Encapsulate the obtained service instance into RibbonServer(ServiceInstance Subclasses of )
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-U5EXjyjK-1623398061695)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/d6b1ad59-c41b-430c-9c64-2b47408976f5/Untitled.png)]](/img/de/5a84caf69951462fe7aa74c83eb2e6.png)
2.LoadBalancerRequest.apply Encapsulate the service instance into HttpRequest Subclasses of ServiceRequestWrapper in
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-xYEZA4Jf-1623398061701)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/695b7d94-7028-4b20-b5c4-2874f37f8596/Untitled.png)]](/img/42/a63dc9e6d2fa57d3a2c63f8bfb0b56.png)
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-fuqQtAy4-1623398061702)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/fc045da1-be11-4ee1-983d-19a37cbb032c/Untitled.png)]](/img/2f/071a125e60f205ead7454af267c2fb.png)
3. Hold ServiceRequestWrapper go back to InterceptionClientHttpRequest Continue to execute , stay getURI Method completes the service name to ip And port replacement process .
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-j6j9Sfk8-1623398061704)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/107f463c-5001-49a9-bd6a-66d90c1c9d5e/Untitled.png)]](/img/57/5b5f28cbb90014e5e73cd7ad83f3ee.png)
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-5ZyaPo1t-1623398061706)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/b027fbc0-c101-4173-a1f5-31eab08f20c5/Untitled.png)]](/img/ed/2e4de9b6d62fefb9056e4da719bcdc.png)
7. Replacement details
@Override
public URI reconstructURI(ServiceInstance instance, URI original) {
// Get an example ID
Assert.notNull(instance, "instance can not be null");
String serviceId = instance.getServiceId();
// Get the context of the load balancer
RibbonLoadBalancerContext context = this.clientFactory
.getLoadBalancerContext(serviceId);
URI uri;
Server server;
if (instance instanceof RibbonServer) {
RibbonServer ribbonServer = (RibbonServer) instance;
server = ribbonServer.getServer();
// Determine whether to use the secure connection
uri = updateToSecureConnectionIfNeeded(original, ribbonServer);
} else {
server = new Server(instance.getScheme(), instance.getHost(), instance.getPort());
IClientConfig clientConfig = clientFactory.getClientConfig(serviceId);
ServerIntrospector serverIntrospector = serverIntrospector(serviceId);
uri = updateToSecureConnectionIfNeeded(original, clientConfig,
serverIntrospector, server);
}
// Take the service instance information and the one with the service name uri Go to replace and return
return context.reconstructURIWithServer(server, uri);
}
Start replacing
public URI reconstructURIWithServer(Server server, URI original) {
String host = server.getHost();
int port = server.getPort();
String scheme = server.getScheme();
// check url Is it consistent with the information in the service instance
if (host.equals(original.getHost())
&& port == original.getPort()
&& scheme == original.getScheme()) {
return original;
}
// Get the request protocol prefix
if (scheme == null) {
scheme = original.getScheme();
}
if (scheme == null) {
scheme = deriveSchemeAndPortFromPartialUri(original).first();
}
try {
StringBuilder sb = new StringBuilder();
// Protocol splicing
sb.append(scheme).append("://");
if (!Strings.isNullOrEmpty(original.getRawUserInfo())) {
sb.append(original.getRawUserInfo()).append("@");
}
// Domain name or ip Splicing
sb.append(host);
// Port integration
if (port >= 0) {
sb.append(":").append(port);
}
// Spell parameters
sb.append(original.getRawPath());
if (!Strings.isNullOrEmpty(original.getRawQuery())) {
sb.append("?").append(original.getRawQuery());
}
if (!Strings.isNullOrEmpty(original.getRawFragment())) {
sb.append("#").append(original.getRawFragment());
}
URI newURI = new URI(sb.toString());
return newURI;
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
In this way, a new link is spliced to send http Request the .
8. Summary
In fact, here will be the whole ribbon Intercept restTemplate I combed the process in detail . We may study it later , How to get the service list , How to update and maintain . There are also different load balancing strategies and how different load balancers play .
边栏推荐
- What happens from the input URL to the page load
- 详解LinkedList
- PHP log base - monolog knowledge collation
- Tencent 5g innovation center was established, laying out key directions such as unmanned ports, smart mines and E-sports events
- [STM32 learning] (11) STM32 Mifare_ Use of one (S50) m1s50 (read, write, key modification, control bit interpretation)
- How to solve command 'xxx GCC' not found, but can be installed with:??
- How does SRE and development of Google cooperate
- Rust tokio:: task:: localset running mode
- PHP debugging tool - socketlog installation and usage
- PHP Basics - PHP super global variables
猜你喜欢

note: expected ‘void * (***)(void ***)’ but argument is of type ‘void (*)(void *)’

Ask you to build a small program server

Server load and CPU performance tuning
![Cyclicbarrier and countdownlatch [concurrent programming]](/img/38/3305a0cdb6de40e1370cc93c8e5014.png)
Cyclicbarrier and countdownlatch [concurrent programming]

Curse of knowledge

Write a simple memo using localstorage

Development history of the first commercial humanoid biped robot in China

In the envy of LETV, there is a "meaning crisis" of contemporary workers

Implementation principle of acid in MySQL

Detailed explanation of uninstalling MySQL completely under Linux
随机推荐
聚集日志服务器
JMeter setting default startup Chinese
JS bind simulation
[MySQL] - deep understanding of index
Set scrolling for the box
详解LinkedList
[STM32 learning] (11) STM32 Mifare_ Use of one (S50) m1s50 (read, write, key modification, control bit interpretation)
Scarcity in Web3: how to become a winner in a decentralized world
Reading makes people improve my list
Recursion - if the function calls itself internally, then the function is a recursive function & the effect is the same as that of the loop & the push condition return should be added, otherwise stack
ThreeJs
Tag the specified commit and submit the tag
缓冲区的概念真的理解么?带你揭开缓冲区的面纱~
Firewalld firewall related commands
It's eleven again. Those jokes about nagging programmers going home for blind dates
Is it safe for Oriental Fortune futures to open an online account, and will it be cheated?
C # +opencvsharp+wpf learning notes (I)
What's the difference between testing / developing programmers' professionalism and salted fish? They don't want to be excellent coders?
Can the "self-help master" who has survived the economic crisis twice continue to laugh this time?
Home raiding III (leetcode-337)