当前位置:网站首页>In depth exploration of ribbon load balancing
In depth exploration of ribbon load balancing
2022-07-26 17:16:00 【Liu Chu, Ge Nian】
List of articles
1. Ribbon Load balancing
Study Eruaka When , We added @LoadBalanced annotation , Load balancing function can be realized , What's the principle ?
1.1 Load balancing principle
SpringCloud The bottom layer is actually using a program called Ribbon The components of , To realize the load balancing function .

Then our request is clearly http://userservice/user/1, How did it become http://localhost:8081 What about ?
1.2 Source tracking
Why do we just input service Name can be accessed ? We need to get ip And port .
Obviously someone helped us according to service name , Get the ip And port . It is LoadBalancerInterceptor, This class will be in the right RestTemplate Request to intercept , And then from Eureka According to the service id Get a list of services , Then we use the load balancing algorithm to get the real service address information , Replace service id.
We are right. LoadBalancerInterceptor Source code tracking :
1)LoadBalancerInterceptor

You can see... Here intercept Method , Intercepted the user's HttpRequest request , Then I did a few things :
request.getURI(): Get request uri, In this case http://user-service/user/8originalUri.getHost(): obtain uri Hostname of the path , It's actually service id,user-servicethis.loadBalancer.execute(): Processing services id, And user requests .
there this.loadBalancer yes LoadBalancerClient type , Let's keep up with execute.
1)LoadBalancerClient
find LoadBalancerClient Interface , Continue to follow in execute Method , Find the subclass that implements the interface :

The code looks like this :
- getLoadBalancer(serviceId): According to the service id obtain ILoadBalancer, and ILoadBalancer Will take the service id Go to eureka Get the list of services in and save it .
- getServer(loadBalancer): Use the built-in load balancing algorithm , Select a... From the list of services . In this case , You can see the capture 8082 Service of port
After release , Visit and track again , We found that 8081:

Sure enough, load balancing is realized .
3) Load balancing strategy IRule
In the code just now , You can see that getting the service through a getServer Method to do load balancing :

Let's keep up with :

Keep track of source code chooseServer Method , Found such a piece of code :

Let's look at this rule Who is it? :

there rule The default is a RoundRobinRule, See the introduction of class :

That's what polling means .
Come here , We know the whole process of load balancing .
4) summary
SpringCloudRibbon The bottom layer of the uses an interceptor , Intercepted RestTemplate Requests made , Changed the address . Summarize with a picture :
The basic process is as follows :
- Intercept our RestTemplate request http://userservice/user/1
- RibbonLoadBalancerClient Will request from url Get the service name from , That is to say user-service
- DynamicServerListLoadBalancer according to user-service To eureka Pull the service list
- eureka Returns a list of ,localhost:8081、localhost:8082
- IRule Leverage built-in load balancing rules , Select one from the list , for example localhost:8081
- RibbonLoadBalancerClient Modify request address , use localhost:8081 replace userservice, obtain http://localhost:8081/user/1, Make a real request
1.3 Load balancing strategy
1.3.1. Load balancing strategy
The rules of load balancing are defined in IRule Interface , and IRule There are many different implementation classes :
The meaning of different rules is as follows :
| Built in load balancing rule class | Rule description |
|---|---|
| RoundRobinRule | Simply poll the list of services to select the server . It is Ribbon Default load balancing rules . |
| AvailabilityFilteringRule | Ignore the following two servers : (1) By default , This server if 3 Secondary connection failed , This server will be set to “ A short circuit ” state . The short circuit condition will continue 30 second , If the connection fails again , The duration of the short circuit will increase geometrically . (2) Servers with too many concurrent . If a server has too many concurrent connections , Configured with AvailabilityFilteringRule The client side of the rule will also ignore it . Maximum number of concurrent connections , It can be done by ..ActiveConnectionsLimit Property configuration . |
| WeightedResponseTimeRule | Give each server a weight value . The longer the server response time , The less weight this server has . This rule randomly selects servers , This weight value will affect the choice of the server . |
| ZoneAvoidanceRule | Select servers based on servers available in the region . Use Zone Classify servers , This Zone It can be understood as a computer room 、 A rack, etc . And then on Zone Polling multiple services in the . |
| BestAvailableRule | Ignore those short circuited servers , And choose a server with a lower number of concurrent . |
| RandomRule | Randomly select an available server . |
| RetryRule | The choice logic of retry mechanism |
The default implementation is ZoneAvoidanceRule, Is a polling scheme
1.3.2. Custom load balancing policies
By defining IRule The implementation can modify the load balancing rules , There are two ways :
Code mode : stay order-service Medium OrderApplication Class , Define a new IRule:
@Bean public IRule randomRule(){ return new RandomRule(); }Configuration file mode : stay order-service Of application.yml In file , Adding a new configuration can also modify the rules :
userservice: # Configure load balancing rules for a microservice , Here is userservice service ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # Load balancing rules
Be careful , Generally, the default load balancing rules are used , No modification .
1.4 Hunger is loaded
Ribbon The default is lazy loading , That is, the first time you visit, you will create LoadBalanceClient, The request will take a long time .
First request :1s
It's very fast to ask again :

Hunger loading will be created when the project starts , Reduce the time-consuming of the first visit , Enable hungry loading through the following configuration :
ribbon:
eager-load:
enabled: true
clients: userservice
边栏推荐
- Who is safe to open the VIP account of CICC securities?
- Marxan model, reserve optimization and protection vacancy selection technology, application in invest ecosystem
- 理财产品锁定期是什么意思?理财产品在锁定期能赎回吗?
- Speaker recruitment | AI time recruit icml/ijcai 2022 as a Chinese speaker!!!
- How to ensure cache and database consistency
- Create MySQL function: access denied; you need (at least one of) the SUPER privilege(s) for this operation
- Tensorflow Lite source code analysis
- Stop supporting Huawei! Signing 640billion 5g orders in Germany and 270billion 5g orders in the Middle East is pure nonsense!
- Redis persistence - detailed analysis of RDB source code | nanny level analysis! The most complete network
- Review the past and know the new MySQL isolation level
猜你喜欢

"Green is better than blue". Why is TPC the last white lotus to earn interest with money

Anaconda download and Spyder error reporting solution

2022-2023 信息管理毕业设计选题题目推荐

The principle of reliable transmission in TCP protocol

Avalanche subnets vs. polygon supernets of application chain

Use verdaccio to build your own NPM private library

Singleton mode

2019普及组总结
![[basic course of flight control development 2] crazy shell · open source formation UAV - timer (LED flight information light and indicator light flash)](/img/ad/e0bc488c238a260768f7e7faec87d0.png)
[basic course of flight control development 2] crazy shell · open source formation UAV - timer (LED flight information light and indicator light flash)

Advantages of time series database and traditional database
随机推荐
如何保证缓存和数据库一致性
Tensorflow Lite source code analysis
极大似然估计
Response对象-响应字符数据
Is the rolling update of pod similar to Canary deployment or blue-green deployment?
Thoroughly uncover how epoll realizes IO multiplexing
[Luogu cf643f] bears and juice (conclusion)
接口比较器
It turns out that cappuccino information security association does this. Let's have a look.
Win11怎么自动清理回收站?
Review the past and know the new MySQL isolation level
My meeting of OA project (meeting seating & submission for approval)
About the idea plug-in I wrote that can generate service and mapper with one click (with source code)
[Development Tutorial 9] crazy shell arm function mobile phone-i2c tutorial
Detailed explanation of tcpdump command
Add 5g and AI, oppo announced to invest 10billion R & D funds next year!
Sharing of 40 completed projects of high-quality information management specialty [source code + Thesis] (VI)
[ctfshow-web]反序列化
How emqx 5.0 under the new architecture of mria+rlog realizes 100million mqtt connections
Take you a minute to learn about symmetric encryption and asymmetric encryption