当前位置:网站首页>[microservice]eureka

[microservice]eureka

2022-06-26 23:26:00 fate _ zore

Eureka

img

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

image-20220622200103526

idea Service replication can be realized

image-20220622200514247

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

image-20220622200603707

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 .

img

Load balancing process

image-20220623114320024

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-server
  • DynamicServerListLoadBalancer according to user-server 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

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

image-20220623135021688

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/8
  • originalUri.getHost(): obtain uri Hostname of the path , It's actually service id,user-service
  • this.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 :

image-20220623135034793

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:

image-20220623135050569

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 :

img

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 :

  1. Code mode : stay order-service Medium OrderApplication Class , Define a new IRule:
@Bean
public IRule randomRule(){
    
    return new RandomRule();
}
  1. 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

原网站

版权声明
本文为[fate _ zore]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206262309254991.html