Use of the registry Eureka

1, Introduction to spring cloud euraka

Spring Cloud Euraka is a component in the Spring Cloud collection. It is an integration of Euraka for service registration and discovery. Eureka is an open source framework in Netflix. Like Zookeeper and consult, it is used for service registration management. Similarly, Spring Cloud also integrates Zookeeper and consult.
Eureka official website document of Spring Cloud: http://cloud.spring.io/spring-cloud-netflix/single/spring-cloud-netflix.html.

2, Eureka role

Eureka is divided into two roles: Eureka Server (Eureka service) and Eureka Client (Eureka Client).
Whether it is a server or a client, it is essentially a Java project. In Spring Cloud, you can distinguish whether the current application is a server or a client by adding @ EnableEurekaServer and @ EnableEurekaClient (which can be omitted) to the startup class.
Eureka Client can be understood as all projects that need to be registered in Eureka Server. Why register with the registry? Because after registration, others can get the project information and the server information of the project through the registration center, and call the project through these information. The information of each project call in the Spring Cloud is stored in the registry (Eureka).

Note: there is no Provider or Consumer in Spring Cloud. If project a accesses project B, project a is called Application Client and project B is called Application Service. At the same time, C may access A. This is that C project is Application Client and a project is Application Service. It is found that project a is both Application Service and Application Client. It mainly depends on which business scenario it is aimed at. Both Applicatin Service and Application Client are Eureka clients.

3, Create stand-alone Eureka Server

Setting up Eureka Server is equivalent to installing Eureka software (a new way to learn in Spring Cloud, which replaces the problem that the corresponding software needs to be installed before).

2.1 create a project. If checked here, Eureka Server dependency will be automatically imported

Add Spring Boot dependency and Eureka Server dependency of Spring Cloud integration.

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
    </parent>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <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-server</artifactId>
        </dependency>
    </dependencies>

2.2 application.yml configuration

eureka:
  client:
    # Because the current project is a service, you do not need to register yourself with the service. The default value is true
    register-with-eureka: false
    # Because it is currently a non clustered version of eureka, there is no need to synchronize the data of other nodes
    fetch-registry: false
# When server The configuration content is required when the port configuration is not 8761
#    service-url:
#      defaultZone: http://localhost:${server.port}/eureka/
server:
  port: 8761

2.3 add @ EnableEurekaServe annotation configuration in startup class

2.4 access

Enter in the browser: http://localhost:8761/.

4, Create Eureka Client

4.1 pom.xml

Refer to the servicer configuration file to add Spring Boot dependency and Eureka Client dependency of Spring Cloud integration.

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

4.2 preparation of configuration files

Add a configuration to the configuration file.
1. The port here is determined so as not to conflict with other projects.
2.spring.application.name is the name after registering with eureka server. You can't use underscores in your name, otherwise you may be unable to register.
3. If Eureka server is configured as a server Port is not 8761. You need to open the following comment and change the port number in the url to the port number configured in the defaultZone in Eureka server. If the port of Eureka server is 8761, the comment part can be omitted.

# The name should be defined here, otherwise the name after registering with the Server is UNKNOWN
spring:
  application:
    name: eureka-client
#eureka:
#  client:
#    serviceUrl:
#      defaultZone: http://localhost:8761/eureka/

4.3 startup

The annotation @ EnableEurekaClient on the startup class can be omitted

4.4 observations

Observe whether the Eureka Client is successfully registered through the visual interface of Eureka Server. If the registration is successful, the registered client information will be displayed in the page.

Application: the name of the application defined in the configuration file
Status: UP indicates that it is executing. smallming is the host name of the server where the client is located. Eureka client defines the application name. If it is 8080 port, it will be omitted. If it is not, it will be displayed later

5, Implementation principle of Eureka cluster

5.1 official schematic diagram

5.2 explanation

All Eureka servers synchronize data through Replicate. No matter which Eureka Server the Eureka Client registers information with, eventually all Eureka servers will store the registered information, which will be cached locally in Eureka Server. The synchronized data in each Eureka Server is identical.
When Eureka Client registers information with Eureka Server, we call it Application Service. When obtaining registered information, it is called Application Client. Because some Eureka Client may need to register services and obtain other services, many Eureka clients are both application services and application clients.
After Eureka Client starts, it sends a heartbeat to Eureka Server every 30 seconds to prove its availability. The heartbeat interval can be modified through the following configuration.

eureka.instance.lease-renewal-interval-in-seconds=30

When Eureka Server does not receive the heartbeat of the provider for more than 90 seconds, it will consider that the provider has been down and destroy the instance. The time can be modified through the following configuration.

eureka.instance.lease-expiration-duration-in-seconds=90

If you restart Eureka Server, all instances will be destroyed.

5.3 self protection mechanism

Eureka has a self-protection mechanism. When more than 85% of Eureka clients do not have normal heartbeat packets within 15 minutes, Eureka believes that there is a network problem between the Server and the Client. At this time, the instance will not be destroyed because no heartbeat is received. Eureka Client can still access the Server, but the Server will not synchronize the content to other servers. When the network is stable, the Server will synchronize the registered information to other servers.
In Eureka, the self-protection mechanism is on by default:

eureka.server.enable-self-preservation=true Boolean

Turn off self-protection

eureka:
  server:
    # Turn off self-protection
    enable-self-preservation: false
    # Scan interval for failed services
    eviction-interval-timer-in-ms: 10000

6, Eureka high availability cluster construction

6.1 write a project and load different parameters through different configuration files.

Finally, deploy the cluster to the server. The cluster is configured with two Eureka servers, and each Eureka Server is installed on a different server.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.5.RELEASE</version>
</parent>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR3</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <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-server</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

6.2 creating profiles

Eureka clusters can be implemented using Spring Boot multiple configuration files. Create several Eureka servers in the cluster and write several configuration files.

application-cluster1.yml

spring:
  application:
    name: eureka1
server:
  port: 8761
eureka:
  instance:
    # And configuration file application XXX Same as YML
    hostname: eurekacluster1
  client:
    service-url:
      defaultZone: http://eurekacluster2:8761/eureka/

application-cluster2.yml

spring:
  application:
    name: eureka2
server:
  port: 8761
eureka:
  instance:
    # And configuration file application XXX Same as YML
    hostname: eurekacluster2
  client:
    service-url:
      defaultZone: http://eurekacluster1:8761/eureka/

6.3 add @ EnableEurekaServer annotation to the main startup class

6.4 mvn plug-in packaging

6.5 uploading linux jar package

[root@base ~]# mkdir -p /usr/local/eurekacluster
[root@base ~]# cd /usr/local/eurekacluster/
#Here, use the tool to upload
[root@base eurekacluster]# ls
eureka_cluster-0.0.1-SNAPSHOT.jar
[root@base eurekacluster]# mv eureka_cluster-0.0.1-SNAPSHOT.jar eurekacluster.jar
[root@base eurekacluster]# ls
eurekacluster.jar

6.6 configure domain name resolution

Modify the / etc/hosts file in the Linux server. The front ip of each line is the ip of the server where the jar is located, and the back name is the hostname value configured in the configuration file in the project

6.7 running with commands

The premise is jdk. The jdk environment variable reference is as follows

Use the command to run Java - Jar - dspring profiles. Active = configuration file variable name jar package name after packaging

java -jar -Dspring.profiles.active=eurekacluster1 eurekacluster.jar 


If it is inconvenient for a character to write commands every time, you can write SHELL script files. Create a new startup.exe in the folder where the jar package is located SH file. Authorization after writing content.

#!/bin/bash
 
cd `dirname $0`
 
CUR_SHELL_DIR=`pwd`
CUR_SHELL_NAME=`basename ${BASH_SOURCE}`
 
JAR_NAME="project jar Package name"
JAR_PATH=$CUR_SHELL_DIR/$JAR_NAME
 
#JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m"
JAVA_MEM_OPTS=""
 
SPRING_PROFILES_ACTIV="-Dspring.profiles.active=Profile variable name"
#SPRING_PROFILES_ACTIV=""
LOG_DIR=$CUR_SHELL_DIR/logs
LOG_PATH=$LOG_DIR/eureka-server.log
 
echo_help()
{
    echo -e "syntax: sh $CUR_SHELL_NAME start|stop"
}
 
if [ -z $1 ];then
    echo_help
    exit 1
fi
 
if [ ! -d "$LOG_DIR" ];then
    mkdir "$LOG_DIR"
fi
 
if [ ! -f "$LOG_PATH" ];then
    touch "$LOG_DIR"
fi
 
if [ "$1" == "start" ];then
 
    # check server
    PIDS=`ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}'`
    if [ -n "$PIDS" ]; then
        echo -e "ERROR: The $JAR_NAME already started and the PID is ${PIDS}."
        exit 1
    fi
 
    echo "Starting the $JAR_NAME..."
 
    # start
    nohup java $JAVA_MEM_OPTS -jar $SPRING_PROFILES_ACTIV $JAR_PATH >> $LOG_PATH 2>&1 &
 
    COUNT=0
    while [ $COUNT -lt 1 ]; do
        sleep 1
        COUNT=`ps  --no-heading -C java -f --width 1000 | grep "$JAR_NAME" | awk '{print $2}' | wc -l`
        if [ $COUNT -gt 0 ]; then
            break
        fi
    done
    PIDS=`ps  --no-heading -C java -f --width 1000 | grep "$JAR_NAME" | awk '{print $2}'`
    echo "${JAR_NAME} Started and the PID is ${PIDS}."
    echo "You can check the log file in ${LOG_PATH} for details."
 
elif [ "$1" == "stop" ];then
 
    PIDS=`ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}'`
    if [ -z "$PIDS" ]; then
        echo "ERROR:The $JAR_NAME does not started!"
        exit 1
    fi
 
    echo -e "Stopping the $JAR_NAME..."
 
    for PID in $PIDS; do
        kill $PID > /dev/null 2>&1
    done
 
    COUNT=0
    while [ $COUNT -lt 1 ]; do
        sleep 1
        COUNT=1
        for PID in $PIDS ; do
            PID_EXIST=`ps --no-heading -p $PID`
            if [ -n "$PID_EXIST" ]; then
                COUNT=0
                break
            fi
        done
    done
 
    echo -e "${JAR_NAME} Stopped and the PID is ${PIDS}."
else
    echo_help
    exit 1
fi

Change jar packages and configuration files

Execute a+x authorization execution

7.8 result inspection

view log

[root@base eurekacluster]# tail -f /usr/local/eurekacluster/logs/eureka-server.log

7.9 because this is not a real domain name, it cannot be accessed directly through the domain name, but the effect of domain name access can be achieved by setting ip mapping, as shown in the figure below


Insufficient permission to change hosts file


Visit again

Client test

eureka:
  client:
    serviceUrl:
      defaultZone: http://eurekacluster1:8761//eureka/,http://eurekacluster2:8761//eureka/


Start the client to observe the eureka cluster

7, Eureka graceful shutdown

Note: Actuator has nothing to do with Eureka. In addition to realizing the effect of Eureka shutdown, it is more important to explain the usage of Actuator to the students.
Eureka's graceful shutdown can be realized with the help of the Actuator (monitor, monitoring center) provided by Spring Boot.
Spring Cloud is based on Spring Boot. Actuator closes the Spring Boot project. All Spring Boot projects and Eureka Server project are closed.
Spring cloud starter Netflix Eureka server depends on the Actuator by default, so there is no need to import additional packages. Normal import is required
eureka server increases dependency

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

Turn on the shutdown function in the configuration file

management:
  endpoints:
    # All functions are enabled by default
    enabled-by-default: true
    # Show all enabled features
    web:
      exposure:
        include: '*'

All functions in Actuator only provide post mode.
Sending POST requests using postman http://localhost:8761/actuator/shutdown.

The observation console has been closed

Keywords: Spring Boot Spring Cloud eureka

Added by dbemowsk on Thu, 06 Jan 2022 13:25:15 +0200