I. Introduction to Eureka

All the code in this article is uploaded to git. Please feel free to browse the project git address: github.com/839022478/S…

In traditional applications, the call between components is realized through the interface with standard constraints, so as to achieve good cooperation between different modules. However, after being divided into micro-services, the network address of each micro-service instance may change dynamically and the number will also change, making the original hard-coded address useless. There is a need for a centralized component to register and manage services. To solve this problem, service governance has emerged, which is to manage all the service information and state, which we call a registry

1.1 Registry

For example, if we want to make a train or a bus, we need to buy a ticket. We only need to see if we have a ticket (service), and then buy a ticket (get the registration list), and then take a bus (call), without caring how many cars in operation

Flow chart:



With registries, we don’t care how many providers there are, we just call them, so what are there?

Registry: Eureka, Nacos, Consul, Zookeeper

This paper introduces Eureka under the popular Spring Cloud microservice. Eureka is a service discovery framework developed by Netflix and a RESTful service. It is a basic component for service discovery and registration and one of the preconditions for setting up Spring Cloud microservice. It hides the details of Server and client interactions, allowing developers to focus on the business.

Service registration and discovery consists of two parts: the Server (Eureka Server) and the Client (Eureka Client).

  • Eureka Server: a public service. It provides service registration and discovery functions for clients, maintains information about clients registered with it, and provides interfaces for clients to obtain information about other services in the registry, enabling dynamic clients to invoke each other.
  • Client (Eureka Client) : The Client registers its service information with the Server in a certain way and maintains its information consistency within the normal range to facilitate other services to discover it. In addition, the Client can obtain information about other services it depends on from the Server to complete service invocation. The Client also has a built-in load balancer for basic load balancing

Eureka GIt website: github.com/Netflix/Eur…

1.3 Service Registration and Discovery

Service registration and discovery diagram:

1.2 Client and Server Functions

1.2.1 client function

  1. Registration: When each microservice starts, it registers its network address and other information with the registry, which stores this information (in memory).
  2. Obtaining the service registry: The service consumer queries the network address of the service provider from the registry and invokes the service provider using the address. To avoid checking the registry information every time, the client periodically pulls the registry information from the server and caches it to the client.
  3. Heartbeat: Each microservice communicates with the registry through some mechanism (heartbeat). If the registry does not communicate with the service for a long time, the instance will be unregistered.
  4. Call: Actual service invocation. Through the registry, the corresponding relationship between the service name and the specific address is resolved to find the address of the specific service for actual invocation.

1.2.2 Server Registry Function

  1. Service registry: record the information of each micro-service, such as service name, IP, port, etc. The registry provides a query API (for querying available microservice instances) and an administration API (for registering and unregistering services).
  2. Service registration and discovery: Registration: Registers microservice information to the registry. Discover: Queries the list of available microservices and their network addresses.
  3. Service check: Periodically checks registered services. If an instance is found to be inaccessible for a long time, it is removed from the registry.

2. Eureka single node construction

2.1 the pom. XML

The spring-boot-starter-web dependency is not needed because the spring-cloud-starter-Netflix-Eureka-server dependency is already included

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
Copy the code

2.2 application. Yml

server:
  port: 8500Eureka: Client: # Whether to register itself with eureka Server. The default value istrue, is set to the serverfalseRegister-with-eureka indicates that the service does not register its information with Eureka:false# Whether to obtain registration information from Eureka server. Since there is only one node, there is no need to synchronize data of other nodesfalse
    fetch-registry: falseDefaultZone: HTTP: / / httpzone: / / httpzone: / / httpzone: / / httpzone: / / httpzone: / ///localhost:8080/eureka/
Copy the code

2.3 Server startup Classes

Adding this annotation to the startup class identifies the service as the configuration center @enableeurekaserver

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); }}Copy the code

2.4 start

We startedEurekaDemoApplication“, and then enter the address in your browserhttp://localhost:8500/, we can start our Eureka, let’s take a look at the effect, this screen appears, it means that we have successfully started ~, but at this time there is no client registration in our service

Service registration

Note: in the client POM we need to addspring-boot-starter-webOtherwise, the service cannot start normally

3.1 the pom. XML

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>     
Copy the code

3.2 application. Yml

Service - URL: defaultZone: HTTP://localhost:8500/eureka/Instance: appname: MXNCopy the code

3.3 Client startup Classes

We need to annotate @enableDiscoveryClient in the client startup class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {

    public static void main(String[] args) { SpringApplication.run(EurekaClientApplication.class, args); }}Copy the code

3.4 Viewing the Effect

After the project starts, refreshhttp://localhost:8500/Page, we can see that the service was successfully registered

DiscoveryClient_MXN/ desktop-5bq3UK8-Registration status: The connection between Eureka Server and Eureka Client is realized through heartbeat. The Eureka Client periodically reports the current status of the service instance to the Eureka Server and maintains the validity of the lease of the service instance in the registry.

The Eureka Client periodically pulls the registry information from the Eureka Server and caches the information locally for service discovery

4. Eureka endpoint

Official website: github.com/Netflix/eur…

The Eureka server also provides an endpoint (Eureka /apps/{applicaitonName}) to view the details of registered services. ApplicaitonName is the name of the micro service, for example, here we go to http://localhost:8500/eureka/apps/mxn

5. Eureka principle

5.1 nature

The registration information for each client is stored. EurekaClient synchronously obtains the service registration list from EurekaServer. Select a service to invoke using certain rules

5.2 Eureka architecture diagram

  • Service provider: a Eureka client that registers and updates its own information with the Eureka Server and obtains information about other services from the Eureka Server registry.
  • Service registry: Provides service registration and discovery capabilities. Each Eureka Cient registers its own information with Eureka Server, and can also obtain information of other services through Eureka Server to discover and invoke other services.
  • Service consumer: Is a Eureka client that uses the Eureka Server to obtain information about other services registered on it, so as to find the required service based on the information to initiate remote calls.
  • Synchronous replication: Synchronous replication of registries between Eureka Servers to ensure the consistency of service instance information in different registries in the Eureka Server cluster.
  • Remote invocation: Remote invocation between service clients.
  • Registration: The Client registers its metadata with the Server for service discovery.
  • Renew: Maintains and updates the validity of service instance metadata in the registry by sending heartbeats to the Server. If the Server does not receive the heartbeat message from the Client within a certain period of time, the service is offline by default and the service instance information is deleted from the registry.
  • Offline: The Client unregisters the service instance metadata to the Server when the Client is shut down. In this case, the service instance data of the Client is deleted from the Server registry.
  • Obtain registry: Client requests registry information from Server for service discovery and remote invocation between services.

5.3 Eureka self-protection

Sometimes we see a message like EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY’RE NOT. RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE. This is because by default, Eureka Server will cancel a micro-service if it does NOT receive a micro-service heartbeat within a certain period of time (90S). But when the network failure, micro can’t normal communication between the Server and service, the behavior is very dangerous, because the service is normal, should not be cancelled, its guiding ideology is better to keep a healthy and unhealthy, also don’t blindly cancel any health services We can also through the command to shut down the self protection function:

eureka:
  server: 
    enable-self-preservation: false
Copy the code

So how is self-preservation triggered? Self protection mechanism of the trigger condition is, when the heartbeat (less than numberOfRenewsPerMinThreshold renewsLastMin) per minute, When eureka.server.enable-self-preservation = true is turned on, the self-preservation mechanism is triggered. No longer automatically expired lease above all our smaller than numberOfRenewsPerMinThreshold, exactly is how to calculate, we can learn that in eureka source

NumberOfRenewsPerMinThreshold = expectedNumberOfRenewsPerMin * relet percentage (0.85 by default) expectedNumberOfRenewsPerMin = current registration number of application examples X 2 The number of registered application instances x 2 is because, by default, registered application instances are renewed every half minute, so heartbeat beats twice a minute, so x 2

For example, we have 10 services, the expected number of renewals per minute: 10 * 2=20, the expected threshold: 20*0.85=17, when less than 17, the self-protection mechanism will be triggered

5.4 Health Check

The server and client maintain service status through heartbeat, and only the services in the UP state can be accessed. Look at the Status in eureka.

For example, the heartbeat is normal all the time and the service is UP all the time, but the service DB(database) cannot be connected. Therefore, the service cannot be provided normally.

At this point, we need to synchronize the health status of the microservice to the server as well. All we need to do is initiate Eureka’s health check. The microservice then synchronizes its health status with Eureka. The configuration is as follows.

Configuration on the client side: Propagates health status to the server.

eureka:
  client:
    healthcheck:
      enabled: true
Copy the code

5.5 Eureka Listening Event

import com.netflix.appinfo.InstanceInfo;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class CustomEvent {

    @EventListener
    public void listen(EurekaInstanceCanceledEvent event ) {
        System.out.println(LocalDateTime.now()+"Service Offline Event :"+event.getAppName()+"-"+event.getServerId());
/ / nailing
    }

    @EventListener
    public void listen(EurekaInstanceRegisteredEvent event) {
        InstanceInfo instanceInfo = event.getInstanceInfo();
        System.out.println(LocalDateTime.now()+"Service Launch Event :"+instanceInfo.getAppName()+"-"+instanceInfo.getInstanceId());
    }

    @EventListener
    public void listen(EurekaInstanceRenewedEvent event) {
        System.out.println(LocalDateTime.now()+"Service Renewal/Heartbeat Reporting event :"+event.getAppName()+"-"+event.getServerId());

    }

    @EventListener
    public void listen(EurekaRegistryAvailableEvent event) {
        System.out.println(LocalDateTime.now()+"Registry Available Events");
    }

    @EventListener
    public void listen(EurekaServerStartedEvent event) {
        System.out.println(LocalDateTime.now()+"Registry Startup Event"); }}Copy the code

5.6 Renew: Service renewal

The Eureka Client sends a heartbeat every 30 seconds to renew the contract. Renew the contract to inform the Eureka Server that the Eureka Client is running properly. By default, if the Eureka Server does not receive a renewal from the Eureka Client within 90 seconds, the Server deletes the instance from its registry. This time is configurable and is not recommended.

5.6 Service Deletion

If Eureka Client is neither renewed nor offline after registration (service crash or network exception), then the service status is unknown and feedback cannot be guaranteed from the service instance. Therefore, it is necessary to remove the service using this method to periodically clean up these unstable services. This method removes all expired leases from the registry in batches. Deleting is a scheduled task that is performed every 60 seconds by default. 60 seconds delay, 60 seconds interval

Restrictions on elimination: 1. Do not remove during self-protection. 2. Remove them in batches.

6. Eureka defect

Because synchronous replication between clusters is carried out through HTTP, due to network unreliability, there are unsynchronized time nodes in the registry information between Eureka servers in the cluster, which does not meet the C(Data Consistency) in CAP.

Seven,

In the middle, we explained the node construction and principle of Eureka. It is very necessary for us to understand Eureka, which is now very hot micro service. If you think the article is helpful to you, please give a thumbs up and support