当前位置:网站首页>[microservice]eureka
[microservice]eureka
2022-06-26 23:26:00 【fate _ zore】
Eureka

order-service How to know user-service Address of the instance ?
- user-service After the service instance starts , Register your information with eureka-server(Eureka Server side ), be called Service registration
- eureka-server Save the mapping relationship between service name and service instance address list
- order-service According to service name , Pull the instance address list , This is called Service discovery Or service pull
order-service How to start from multiple user-service Select a specific instance from the instance ?
order-service Use... From the list of instances Load balancing algorithm Select an instance address , Make a remote call to the instance address
order-service How to learn about a user-service Whether the instance is still healthy , Is it down ?
- user-service Meeting Every once in a while ( Default 30 second ) towards eureka-server Initiate request , Report your status , be called heartbeat
- When no heartbeat is sent over a certain period of time ,eureka-server It will be considered that the microservice instance has failed , Remove the instance from the service list
- order-service When pulling Services , You can eliminate the fault instance
build EurekaServer
build eureka-server
introduce SpringCloud by eureka Provided starter rely on , Note that here is server
Introduce dependencies
<!-- eureka-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
The configuration file
server:
port: 10086 # Service port
spring:
application:
name: eureka-server # Microservice name
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka/ #eureka Address information
among default-zone The reason is that the previous configuration class opens the configuration required by the registry eureka Of Address information , because eureka It is also a micro service , You should also register yourself here , When the back eureka colony when , Here you can fill in multiple , Use “,” separate .
register eureka-server
Introduce dependencies
<!-- eureka-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
Modify the configuration file
spring:
application:
name: ****** # Microservice name
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka/ #eureka Address information
Registered successfully

idea Service replication can be realized

But to avoid port conflicts , Port number needs to be reset -Dserver.port= Port number

Service pull
stay order-service Complete service pull in , Then select a service through load balancing , Implement remote call
First of all RestTemplate This Bean Add one @LoadBalanced annotation , For opening Load balancing
/** * establish RestTemplate And injection spring Containers */
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
modify OrderService Access to the url route , use service name Instead of ip、 port :
public Order queryOrderById(Long orderId) {
// 1. Query order
Order order = orderMapper.findById(orderId);
// 2. utilize restTemplate Initiate request , Query the user
String url = "http://user-server/user/" + order.getUserId();
User user = restTemplate.getForObject(url, User.class);
order.setUser(user);
// 4. return
return order;
}
Ribbon Load balancing
We added @LoadBalanced annotation , Load balancing function can be realized , What's the principle ?
SpringCloud The bottom layer provides a file called Ribbon The components of , To achieve load balancing function .

Load balancing process

The basic process is as follows :
- Intercept our
RestTemplaterequest http://userservice/user/1 RibbonLoadBalancerClientWill request from url Get the service name from , That is to say user-serverDynamicServerListLoadBalanceraccording to user-server To eureka Pull the service list- eureka Returns a list of ,localhost:8081、localhost:8082
IRuleLeverage built-in load balancing rules , Select one from the list , for example localhost:8081RibbonLoadBalancerClientModify request address , use localhost:8081 replace userservice, obtain http://localhost:8081/user/1, Make a real request
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 do source tracking :
1)LoadBalancerIntercepor

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 .
2)LoadBalancerClient
Continue to follow in execute Method :

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 .
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 , Can be set by the client . |
| 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 .
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 :
user-server: # 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 .
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 .
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: user-server # This is a list
边栏推荐
- Different subsequence problems I
- 分享三种在Excel表格中自动求和的方法
- golang语言的开发学习路线
- 入侵痕迹清理
- Share three methods of automatic summation in Excel
- Unityeditor Editor Extension - table function
- 数据清洗工具flashtext,效率直接提升了几十倍数
- Is it safe to open an account on the mobile phone to buy stocks? Is it safe to open an account on the Internet to speculate in stocks
- L'outil de nettoyage des données flashtext améliore directement l'efficacité de plusieurs dizaines de fois
- [mixed programming JNI] Part 9: JNI summary
猜你喜欢

50 tips that unity beginners can definitely use
![[machine learning] - Introduction to vernacular and explanation of terms](/img/4c/e18fe52a71444c2ca08167ead9f28f.jpg)
[machine learning] - Introduction to vernacular and explanation of terms

微信小程序自动生成打卡海报

Reading graph augmentations to learn graph representations (lg2ar)

Microservices, an important part of cloud native architecture

阿里云服务器的购买、基本配置、(xshell)远程连接、搭建环境

WP collection plug-in tutorial no thanks for WordPress collection of rules

Implement the queue through two stacks

Nacos安装指南

Typera set title auto numbering
随机推荐
FPGA -VGA显示
typora设置标题自动编号
Three solutions for improving embedded software development environment
运筹说 第66期|贝尔曼也有“演讲恐惧症”?
Different subsequence problems I
简单测试轻量级表达式计算器Flee
[mixed programming JNI] Part 6: operation of strings and arrays in native
WordPress collection plug-ins are recommended to be free collection plug-ins
C language: a simple calculator is implemented by using code many times
Open world mecha games phantom Galaxy
Microservices, an important part of cloud native architecture
Why don't I recommend going to sap training institution for training?
在手机开户买股票安全吗 网上开户炒股安全吗
Selenium电脑上怎么下载-Selenium下载和安装图文教程[超详细]
Color matching and related issues
The processing of private chat function in go language
从位图到布隆过滤器,C#实现
买基金在哪里开户买比较安全
go语言的爬虫和中间件
【强基计划】数学与物理竞赛中的微积分部分视频