Introduction and Use of the SpringCloud-Service Registry "Eureka"

Posted by Erik-NA on Mon, 20 Apr 2020 03:06:11 +0200

Two components of Eureka

(vi)Eureka Server: Provides service registration services

After each micro-service node is started by configuration, it will be registered in Eureka Server, so that the service registry in Eureka Server will store information of all available service nodes, and the information of service nodes can be visualized in the interface.

(vi)Eureka Client: Accessed through the Service Registry

Is a Java client that simplifies the interaction of Eureka Server. The client also has a built-in load balancer that uses a round-robin load algorithm and sends a heartbeat (default cycle is 30 seconds) to Eureka Server when the application starts.If Eureka Server does not receive a node's heartbeat during multiple heartbeat cycles, Eureka Server will remove the service node from the service registry (default 90 seconds).

Eureka Server Build

List only the important parts. Detailed code can be found in here Get~

1. Import Maven Dependencies in Registry Service

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

2. Write a configuration file

server:
  port: 7001
eureka:
  instance:
    # Instance name of eureka server side
    hostname: localhost
  client:
    # false means that you do not register yourself with the registry
    register-with-eureka: false
    # false says that my client is the registry and my responsibility is to maintain service instances without having to retrieve services
    fetch-registry: false
    # This address is required for setting up an address query service and registration service to interact with Eureka Server
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

3. Turn on Eureka service registration in the main startup class

@SpringBootApplication
@EnableEurekaServer //Turn on service registration
public class EurekaMain7001 {
    public static void main(String[] args) {
        SpringApplication.run(EurekaMain7001.class, args);
    }
}

4. Open browser input: http://localhost:7001/, enter Eureka service panel successfully, basic configuration is completed

Eureka Client Registration

1. Add a client's Maven dependency to the Service Provider

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

2. Add Configuration

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka #Registry Address

3. Open the Eureka server in the main startup class

@SpringBootApplication
@EnableEurekaClient
public class PaymentMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain8001.class);
    }
}

4. Enter the registration panel to discover that the service has been registered

5. By registering "Service Consumer" as above, we have built a simple single-machine version of Eureka environment.

Problem with single-machine version Eureka

What is the core of microservice RPC remote service calls?

High Availability!Imagine that if you only have one registry center, it fails and the entire microservice environment becomes unavailable, so we can achieve load balancing + fault tolerance by building an Eureka registry cluster.

Explanation of Eureka Cluster Principle:

Set up Eureka Cluster

1. In order to simulate a cluster, we need to modify the host file

# SpringCloud Eureka Cluster Configuration
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com

2. Create a new project as the Eureka Service Registry with the following configuration files

server:
  port: 7002

eureka:
  instance:
    # Instance name of eureka server side
    hostname: eureka7002.com
  client:
    # false means that you do not register yourself with the registry
    register-with-eureka: false
    # false says that my client is the registry and my responsibility is to maintain service instances without having to retrieve services
    fetch-registry: false
    # This address is required for setting up an address query service and registration service to interact with Eureka Server
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/

3. Modify the configuration of the previous project to complete the mutual registration between the two registries

server:
  port: 7001

eureka:
  instance:
    # Instance name of eureka server side
    hostname: eureka7001.com
  client:
    # false means that you do not register yourself with the registry
    register-with-eureka: false
    # false says that my client is the registry and my responsibility is to maintain service instances without having to retrieve services
    fetch-registry: false
    # This address is required for setting up an address query service and registration service to interact with Eureka Server
    service-url:
      defaultZone: http://eureka7002.com:7002/eureka/

4. Access: http://eureka7001.com:7001/and http://eureka7002.com:7002/

5. Since there are now two registries, we need to change the defaultZone configuration from the previous one to the following. After restarting, you can see that there are other services in both registries.

defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

6. Create a new service provider that can directly copy the previous code, start the service, refresh the registry, and now have two service providers

7. At this point, service consumers are constantly invoking providers in a polling load-balanced manner

8. Service Name and Access Information Prompt IP Address can be configured as follows

eureka:
  instance:
    instance-id: payment8001
    prefer-ip-address: true   #Access path can display ip address

If you introduce an actuator

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Service Discovery

1. Injecting DiscoveryClient

@Autowired
private DiscoveryClient discoveryClient;

2. Getting service information

@GetMapping("/payment/discovery")
public Object discovery() {
    List<String> services = discoveryClient.getServices();
    for (String service : services) {
        log.info("service:" + service);
    }

    List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
    for (ServiceInstance instance : instances) {
        log.info("serviceId:" + instance.getServiceId() + "\t" + "Host:" + instance.getHost() + "\t" + "port:" + instance.getPort() + "\t" + "uri:" + instance.getUri());
    }

    return this.discoveryClient;
}

3. Add @EnableDiscoveryClient on the main startup class to turn on service discovery

Eureka self-protection

On the Eureka registry page you will see a reminder that Eureka is in protected mode

The protection mode is mainly used for protection in a network partition scenario where a set of clients and Eureka Server exist.Once in protected mode, Eureka Server will attempt to protect the information in its service registry without deleting the data in the service registry, that is, without unregistering any microservices.

Simply put: a microservice is not available at any time, Eureka will not clean up immediately, but will still save the information of the microservice; belonging to AP branch of CAP theory

_Why does Eureka self-protection occur?

To prevent the EurekaClient from functioning properly, but not immediately excluding the EurekaClient service if it is not connected to the EurekaServer network

_What is a self-protection model?

By default, if EurekaServer does not receive a heartbeat for a microservice instance for a certain period of time, EurekaServer will log off the instance (default 90 seconds).However, when network partition failures occur (latency, carton, congestion), the normal communication between the microservice and EurekaServer can become very dangerous because the microservice itself is healthy and should not have been logged off at this time.Eureka solves this problem through "self-protection mode" - when an Eureka Server node loses too many clients in a short period of time (network partition failure may occur), it enters self-protection mode.

In self-protection mode, EurekaServer protects information in the service registry and no longer logs out any service instances.

Its design philosophy is to retain incorrect service registration information rather than blindly deregister any potentially healthy service instances.One sentence: Better to live than to die I

To sum up, self-protection mode is a kind of security protection against network anomalies.Its architecture philosophy is to prefer to keep all microservices (both healthy and unhealthy) at the same time without blindly deregistering any healthy microservices.Using self-protection mode, you can make the Eureka cluster more robust and stable.

_How to disable self-protection mode

Add the following to the registry service configuration

eureka:
  server:
    # Turn off self-protection to ensure unavailable services are removed in time
    enable-self-preservation: false
    eviction-interval-timer-in-ms: 2000

Refresh the registry page to see that the alert content has changed and the self-protection mode has been turned off

Add the following to other service configurations

eureka:
  instance:
    # The time interval between Eureka clients sending heartbeats to the server in seconds (default is 30 seconds)
    lease-renewal-interval-in-seconds: 1
    # The maximum wait time for the Eureka server after receiving the last heartbeat in seconds (default is 90 seconds), and the timeout will exclude the service
    lease-expiration-duration-in-seconds: 2

When the service is started normally, the service appears in the registry list. When we close the service and look at the list again, we can see that the service is directly excluded within 2 seconds

Eureka2.0 Stop and Change Statement

This is Eureka's official statement

Although it has stopped updating and now has a better alternative, its ideas are similar and it is still worth learning.

Topics: network Spring Maven Java