Euraka profile

Euraka is an open source framework developed by Netflix. Spring-cloud Euraka is Euraka’s Spring Cloud component. Of course, Spring-Cloud also integrates components such as Zookepper and Consul. They can both implement the process associated with service discovery.

Euraka with a Zookeeper

In current Web development, Euraka is mainly used for the following reasons:

  • Zookepper focuses on consistency and fault tolerance of partitions and does not skew availability enough. In most web applications, there is actually more emphasis on usability. Of course, Zookepper can also be used in some projects requiring strong consistency, such as bank account information synchronization and other service management.
  • Euraka focuses on availability and partition fault tolerance, which is suitable for daily Web development.

Tips:

Service discovery supports registration and discovery of services developed in other languages, and the microservices architecture better provides a heterogeneous toolset. Why use Euraka as a service discovery tool can be found in this article: dockone. IO /article/78

This reference article:

www.itmuch.com/spring-clou… Spring tutorial series by Teacher Zhou Li

I just did a detailed description of the example in this article, and some basic, easy to confuse the point to do the details of the supplement, you can first see Zhou Li’s tutorial, and then come here to supplement some basic concepts.

1 New key for a distributed service

  1. Open the IDEA new key console project
  2. Add framework support –> Maven
  3. The pom. XML file content is as follows:
<? xml version="1.0" encoding="UTF-8"? > <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> < modelVersion > 4.0.0 < / modelVersion > < groupId > org. Bruce. Study < / groupId > < artifactId > UserRegisterService < / artifactId > 1.0 the SNAPSHOT < version > < / version > < packaging > jar < / packaging > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.0.7. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> < project. Reporting. OutputEncoding > utf-8 < / project. Reporting. OutputEncoding > < Java version > 1.8 < / Java version > </properties> <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-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> < version > 1.18.12 < / version > < scope > provided < / scope > < / dependency > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <! --> <dependency> <groupId>com.h2database</groupId> <artifactId> H2 </artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> <! -- Introducing spring Cloud dependencies <dependencies> <dependency> <dependencies> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.SR2</version> <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Copy the code

Key point description

Since Spring Cloud has many versions, you need to configure the parent node of Spring Boot in Maven. This node specifies the version of Spring Boot used by the current Web project:

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> The < version > 2.0.7. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent>Copy the code

You also need to specify the version number of the Current Spring Cloud using the dependencyManagement node:

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
Copy the code

Note that:

Why doesn’t Spring Boot use the latest version? (As of this writing, the latest version of Spring Boot is 2.3.1)

Different versions of Spring Cloud require different Versions of Spring Boot. For details, see the following table:

The version number instructions Is it recommended?
Only digital version number Development version Development team internal use, not very stable
GA Stable version Compared to the development version, it is almost ready to use
PRE (M1, M2) Milestone version A GA usually has more than one milestone release
RC Release candidate This phase of the software is similar to a release watch period for the final version, with only the most serious bugs being fixed
SR Official Release A production-ready version

+ + https://start.spring.io/actuator/info++ Spring Cloud with Spring Boot version compatibility rules see release notes related to this url (JSON format)

With Maven configuration, we build distributed services using:

  • The H2 database
  • JPA
  • Spring Boot
  • spring-cloud-starter-netflix-eureka-client

> Spring-cloud-starter-netflix-eureka-client is used to identify the current distributed service as a Eureka client. Eureka clients will be able to register with the Eureka server.

Write a distributed service

package org.bruce.study.controller;

import org.bruce.study.Entities.User;
import org.bruce.study.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserDao userDao;

    @GetMapping("/{id}")
    public Optional<User> getUserById(
            @PathVariable
                    Integer id) {
        returnthis.userDao.findById(id); }}Copy the code

Learn Spring Boot 2.0.x by yourself.

So our service provides a service that queries users by their ID and provides a Get request.

3 Set service running parameters

Application. Yml file

server:
  # Specify a Tomcat port
  port: 8088
spring:
  application:
    name: userservice
  jpa:
    Let Hibernate print the executed SQL
    show-sql: true

logging:
  level:
    root: INFO
    Configure the logging level so that Hibernate prints out the SQL parameters executed
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
management:
  endpoint:
    health:
      Whether to display health check details
      show-details: always
eureka:
  client:
    service-url:
      Eureka server address: /eureka/
      defaultZone: http://localhost:8761/eureka/
  instance:
    If not specified or set to false, the host name will be registered with the Eureka server
    prefer-ip-address: true

Copy the code

Tips:

  • Specify the current service running port 8088
  • The name of the service is specified as userServcie, noting that this is the name of the current service registered with Eureka service discovery.
  • Management: specifies the current Spring Boot running monitoring.
  • The Eureka node specifies the details of the current service discovery. The client node refers to the configuration of the current Eureka client. Generally, the address of the service discovery server is specified in this node.
  • Eureka-instance Configures information about the Eureka client instance on the current node.

Important Eureka client configuration items

The Client nodes:

Configuration items instructions
region Default service partition where the current client resides (default: US-east-1)
availability.zones Configure available zones of a region. Multiple zones are separated by commas (,). The system will load the zones from the preceding URLS first based on the configured sequence
serviceUrl Use commas (,) to separate multiple server addresses
registry-fetch-interval-seconds Time step of obtaining the latest registration information from the server, in seconds. If the fetch times out, the second fetch time is doubled
register.with.eureka Whether to register the current service with the Eureka server. If the value is set to false, the current service only obtains the address of other services, if it is not registered with the Eureka server. This protects some private interface access (such as the employee identity token authentication service, which only invokes external service discovery but is not itself registered with the Eureka server).
fetch.registry Specifies whether to obtain registration information from the server. Set this parameter to True if the server is a cluster.
instance-info-replication-interval-seconds Time step of scanning the local instance, in seconds. Re-register the current service with the Eureka server if there are changes.

The instance node:

Configuration items instructions
lease-renewal-interval-in-seconds Time step of the heartbeat to the server, in seconds. When the Eureka client successfully communicates with the server for the first time, the server will return 404. The client will then register the local instance. If the registration succeeds, the server will return 200.
prefer-ip-address When a Eureka client registers with the Eureka server, the current service is registered using an IP address or a host name. (Suggestion: IP)
ip.address The current Eureka client specifies the IP address of the Eureka instance. If this parameter is not specified, the non-loopback address of the first NIC is used by default.
lease-expiration-duration-in-seconds The current time step for the Eureka server to expel the client, in seconds. The Eureka server removes some inaccessible Eureka clients when certain conditions are met. If the Eureka server does not receive a client heartbeat for more than 90 seconds and the client is not self-protected, the Eureka server ejects the client. If the self-protection function is enabled on the client, the client is also expelled if the number of registered clients in the last minute > the number of heartbeat messages received from the client in the last minute * the renewal factor (0.85) per minute is enabled.

Through the configuration we need to know the main knowledge points

  • Eureka Client is the decorator that registers the current service to Eureka Server.
  • The Eureka Client itself is a Eureka Instance.
  • The Eureka Client uses the heartbeat to inform the Eureka Server of the current service status.
  • If the Eureka Server does not receive heartbeat messages from a Eureka Client for a period of time, the Eureka Server logs out of the Eureka Client.
  • The Eureka Client is used to discover services and is not registered with the Eureka Server.
  • Region: A physical Region of the Eureka service. Distributed services may be built in different machine rooms in different regions. In order to reduce the physical delay of inter-service invocation, we always hope that inter-service invocation should call local services first to reduce the delay caused by network transmission. Region Refers to the Region of the current server. It can be regarded as a service classification identifier based on server geographical location.
  • Zone:Zone can be considered as a subclassification based on Region. For example, we have multiple machine room clusters, one in Beijing and one in Shanghai. The machine room cluster in Beijing may have multiple servers, such as server S1 and server S2. In this case, we can identify the Zone of server S1 as S1 and the Zone of server S2 as S2. This allows for efficient physical separation of request directions, further reducing cross-server calls and latency.

Write the Eureka Server

1. Create a console project for Idea

Project name: EurekaDemoServer

2. Add Maven support

The pom.xml file looks like this:

<? xml version="1.0" encoding="UTF-8"? > <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> < modelVersion > 4.0.0 < / modelVersion > < groupId > org. Bruce. Study < / groupId > < artifactId > EurekaDemoServer < / artifactId > < version > 1.0 - the SNAPSHOT < / version > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.0.7. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> < project. Reporting. OutputEncoding > utf-8 < / project. Reporting. OutputEncoding > < Java version > 1.8 < / Java version > </properties> <dependencies> <! -- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-server --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <! -- Introduce spring Cloud dependencies, not less, <dependency management > <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.SR2</version> <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Copy the code

For details about the Spring Cloud version and Spring Boot version, see the previous part of this chapter

3. Add the EurekaServer startup class

package org.bruce.study; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurecaDemoServer { public static void main(String[] args) { SpringApplication.run(EurecaDemoServer.class, args); }}Copy the code

Annotated with @enableEurekaserver, this class is considered to be EurekaServer’s startup class.

4. Add the application.yml configuration

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:8761/eureka/
Copy the code

Easy to lead to confusion

Why are Client and Instance configured in Eureka Server configuration?

A: Any Eureka Server is first and foremost a Eureka Client. Any Eureka Clent is a Eureka Instance.

Tips:

Recall the IS A principle.

Why do they do that?

A: Eureka Instance is a Eureka Instance, which mainly contains basic network communication mechanisms such as heartbeat, service status return, etc. The Eureka Client can be thought of as an extension of Eureka Instance, providing more practical configurations, including ease-of-use configurations such as obtaining IP addresses. As for why this design? This is to ensure that Eureka Server can also be registered as a Eureka Client on other Eureka servers.

tips:

Multiple Eureka Server instances synchronize data in the service registry through incremental replication.

What does that mean?

I made an order payment service in the mall. Eureka Server1 is deployed on the server in Shenzhen, and Eureka Server2 can be registered on the server in Shenyang. Eureka Server2 can also be registered with Eureka Server1. The services of Eureka Server1 and Eureka Server2 will be incrementally updated to their service registries so that user access will not become inaccessible due to the failure of a single server, thus ensuring high availability.

Some confusion in Eureka configuration

Long Long time ago, Netfix wrote Eureka to give all of America access to their services deployed on Amazon’s cloud. So the Eureka configuration retains many of the concepts associated with Amazon Cloud, such as scaling services and so on. However, it must be understood that As an ancestor cloud service, Many concepts of Amazon Cloud exist in other cloud services. As it has become a habit, people are using these concepts, so Eureka can be deployed and run seamlessly no matter in Alibaba cloud or Tencent cloud. So there is no need to worry about remaining concepts unique to Amazon Cloud, such as THE ASG, in Eureka configuration, which can be found in other cloud services.