Spring Cloud eureka-Service registration and discovery

Source: Internet
Author: User
Tags spring initializr

Spring Cloud Eureka

Spring Cloud is one of the mainstream frameworks currently used to develop microservices, and we all know that the most basic and core modules in the MicroServices architecture are service registration and discovery.

In spring cloud, we can use its Eureka module for service registration and discovery, and Spring Cloud Eureka is based on the Netflix Eureka two times, and it is primarily responsible for automating the registration and discovery of each micro-service instance.

The Eureka consists of two components:

    • Eureka Server (Registration Center)
    • Eureka Client (Service registration)

Why service discovery is required in a distributed system:

In the actual distributed environment, the architecture is often no longer a few servers, but each individual service runs on multiple machines. For example, a service is deployed on 10 machines, B services are also deployed on 10 machines, and C services are deployed on 5 machines.

Now some of the functions of a service need to invoke the B service to implement, then the question is, how can a service call B service? In general, we can think of all the machine addresses where the B service is located, configured to the a service through the configuration file, so that it can find and invoke the B service through the configured address.

This is also a feasible approach, but the addresses of these machines are subject to change, and some service outages can occur in the production environment, which can lead to some cascading effects. With the expansion of the business, the machines will be more and more, and there is no way to manually configure the machine address by the configuration file.

Given the lazy nature of human beings ... Yuck, in view of the human pursuit of efficient work, a better life. So the tools dedicated to service registration and discovery were developed in one by one. With the Service governance framework, service discovery can be left to it for automated completion. At this time a service only need to go to the registry for service registration, the same B service also to the registration Center for service registration. Once registered, the registry will confirm the survival of the service through a heartbeat-like mechanism. If you confirm that a service is down, the registry will remove the service from the outage. When a service to invoke the B service, then to the registry to get the B service call address, B service calls a service also the same. The registry is the equivalent of a service and service bridge or intermediary, can say to help us manage the service between the trivial.

Eureka Service governance system is as follows:

The Spring Cloud website address is as follows:

https://projects.spring.io/spring-cloud/

Eureka Server

Needless to say, in this section we will build a Eureka Server, the service registry. Open idea and create a new spring INITIALIZR project:

Tick the Eureka Server module:

To complete the creation of the project:

The contents of the Pom.xml file generated by the project are 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.zero</groupid > <artifactId>eureka</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>j Ar</packaging> <name>eureka</name> <description>demo Project for Spring boot</description > <parent> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot -starter-parent</artifactid> <version>2.0.4.RELEASE</version> <relativePath/> <!- -Lookup parent from repository-</parent> <properties> <project.build.sourceencoding&gt ; Utf-8</project.build.sourceencoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version >1.8</java.version> <spring-cloud.version>Finchley.SR1</spring-cloud.version> </properti es> <dependencies> <dependency> &LT;GROUPID&GT;ORG.SPRINGFRAMEWORK.CLOUD&LT;/GROUPID&G            T <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <depe Ndency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-sta rter-test</artifactid> <scope>test</scope> </dependency> </dependencies&gt    ; <dependencyManagement> <dependencies> <dependency> <groupid>org.s             Pringframework.cloud</groupid> <artifactId>spring-cloud-dependencies</artifactId>   <version>${spring-cloud.version}</version> <type>pom</type> <s    cope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> &LT;GROUPID&GT;ORG.SPRINGFRAMEWORK.BOOT&L        T;/groupid> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>

Note: The version of the Springboot and Springcloud components has a corresponding relationship, this on the official website has a detailed comparison chart. It is important to note that Springcloud does not identify the version number in the form of 2.0.1, but instead identifies the version number with the name of the London metro station, and the names are in alphabetical order.

Once the project is created, we can try to start it, but before starting it, we need to add annotations in the Startup class to @EnableEurekaServer enable Eureka Server, otherwise the access will be reported 404. The code is as follows:

package org.zero.eureka;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@SpringBootApplication@EnableEurekaServerpublic class EurekaApplication {    public static void main(String[] args) {        SpringApplication.run(EurekaApplication.class, args);    }}

After you start the project, the pages that have access to the following Eureka registries represent success:

At this point, although the normal access to the registry page, but will find the console has been an error, prompt Cannot execute request on any known server . This is because the Eureka server is both a server and a client, and it also needs to register itself in a registry. Because we did not configure the registry address, so it can not register themselves will report this error.

In this case, we just need to configure the address of the registry, edit the Application.yml configuration file content as follows:

eureka:  client:    service-url:      defaultZone: http://localhost:8761/eureka/  # 指定注册中心的url    register-with-eureka: false  # 指定不进行注册操作,默认为true,若进行注册的话,会显示在Eureka信息面板上  server:    enable-self-preservation: false  # 禁用eureka server的自我保护机制,建议在生产环境下打开此配置spring:  application:    name: eureka  # 指定应用的名称server:  port: 8761  # 指定项目的端口号

Note: Because the server and client are using the heartbeat mechanism to confirm survival, the process of starting the project may still be an error. However, as long as the startup is not always error, and can normally access the Eureka Information Panel page, the project is in the normal operation

Use of the Eureka client

In the previous section, we briefly described how to create and configure a Eureka server project. Now that we know how to build Eureka Server, we'll cover the use of Eureka Client in this section, and we'll show you how to register a service with Eureka client.

Similarly, use idea to create a spring INITIALIZR project, except that you need to select Eureka Discovery when checking the module, as follows:

The contents of the Pom.xml file generated by the project are 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.zero.eureka</ groupid> <artifactId>client</artifactId> <version>0.0.1-SNAPSHOT</version> <packagi Ng>jar</packaging> <name>client</name> <description>demo Project for Spring Boot</desc ription> <parent> <groupId>org.springframework.boot</groupId> <artifactid>spri  Ng-boot-starter-parent</artifactid> <version>2.0.4.RELEASE</version> <relativePath/> <!--lookup parent from repository--</parent> <properties> <project.build.sourceenco Ding>utf-8</project.build.sourceeNcoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java. Version>1.8</java.version> <spring-cloud.version>Finchley.SR1</spring-cloud.version> </p roperties> <dependencies> <dependency> <groupid>org.springframework.cloud</gr Oupid> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependenc y> <dependency> <groupId>org.springframework.boot</groupId> <artifact    Id>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency>                </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactid>spring-cloud-dependencies&      Lt;/artifactid>          <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencymanageme nt> <build> <plugins> <plugin> <groupid>org.springframework .boot</groupid> <artifactId>spring-boot-maven-plugin</artifactId> </plugin&        Gt </plugins> </build></project>

When the dependencies of the project are loaded, add in the Startup class @EnableDiscoveryClient , declare that this is a Eureka client, otherwise the service registration will not be done:

package org.zero.eureka.client;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication@EnableDiscoveryClientpublic class ClientApplication {    public static void main(String[] args) {        SpringApplication.run(ClientApplication.class, args);    }}

Then, in the APPLICATION.YML configuration file, configure the address of the registry, Eureka Server, and the name and startup port number of the project. As follows:

eureka:  client:    service-url:      defaultZone: http://localhost:8761/eureka/spring:  application:    name: eureka-clientserver:  port: 9088

Once you have completed the above configuration, you can start the project. But I failed to start the project here, the console output the following warning message:

Invocation of Destroy method failed on beans with name ' scopedtarget.eurekaclient ': Org.springframework.beans.factory.BeanCreationNotAllowedException:Error creating bean with Name ' Eurekainstanceconfigbean ': Singleton bean creation not allowed while singletons of this factory is in destruction (does not Request a bean from a beanfactory in a destroy method implementation!)

This is because the client does not contain Tomcat dependencies, so the spring container cannot create some instances, causing the project to fail to start, just in the Pom.xml file, plus Web dependencies:

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

Once the project has started successfully, you can see the registered instance information in the information panel of the Eureka server as follows:

Eureka High-availability

High availability is a frequently occurring term in the service architecture design. In the MicroServices architecture it is also natural to ensure high availability of services, so this section will briefly explain how Eureka is highly available.

In a real-world production environment, servers are fragile, and a single server must not meet high-availability requirements, and in order to ensure high availability we usually prepare multiple servers. However, it can be found that the Eureka server set up above is a single machine, and if this Eureka server goes down, it will cause all of the microservices associated with it to fail.

Since the stand-alone is not guaranteed to be highly available, we'll add one more machine, and then let the two Eureka servers correlate with each other. For example I now have two Eureka servers. One named Eureka-server01 ran on Port 8761, and the other named Eureka-server02 ran on port 8762. Then it takes only two steps to achieve a high availability:

    • 1. Edit the configuration files of these two Eureka servers so that their registered addresses point to each other and can be linked together
    • 2. In the Eureka client configuration file, configure the addresses of the two Eureka servers so that the client can be registered to both Eureka servers at the same time. So even if one of the Eureka servers hangs up, the other one can still work.

1. Edit the configuration files for the two Eureka servers, Eureka-server01:

eureka:  client:    service-url:      defaultZone: http://localhost:8762/eureka/  # 指向eureka-server02的url    register-with-eureka: false  server:    enable-self-preservation: false spring:  application:    name: eureka-server01 server:  

Eureka-server02:

eureka:  client:    service-url:      defaultZone: http://localhost:8761/eureka/  # 指向eureka-server01的url    register-with-eureka: false  server:    enable-self-preservation: falsespring:  application:    name: eureka-server02 server:  

2. Edit the Eureka client configuration file, with multiple URLs separated by commas:

eureka:  client:    service-url:      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/spring:  application:    name: eureka-clientserver:  port: 9088

If the project size is larger, there are more than two Eureka server, then how to configure in the configuration file? In fact, each Eureka server is only required to configure Eureka server machines other than itself, and then Eureka client configures all Eureka server addresses. Such as:

Configuration file example, Eureka-server01:

eureka:  client:    service-url:      defaultZone: http://localhost:8762/eureka/,http://localhost:8763/eureka/    register-with-eureka: falsespring:  application:    name: eureka-server01 server:  

Configuration file example, Eureka-server02:

eureka:  client:    service-url:      defaultZone: http://localhost:8761/eureka/,http://localhost:8763/eureka/    register-with-eureka: falsespring:  application:    name: eureka-server02 server:  

Configuration file example, Eureka-server03:

eureka:  client:    service-url:      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/    register-with-eureka: falsespring:  application:    name: eureka-server03 server:  

Sample configuration file for Eureka client:

eureka:  client:    service-url:      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/,http://localhost:8763/eureka/spring:  application:    name: eureka-clientserver:  port: 9088

Spring Cloud eureka-Service registration and discovery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.