使用Eureka註冊服務



本章將詳細講解如何將Spring Boot微服務應用程式註冊到Eureka Server。在註冊應用程式之前,請確保Eureka Server正在8761埠執行,或者首先構建Eureka Server並執行它。有關構建Eureka伺服器的更多資訊,您可以參考上一章Spring Boot - Eureka Server

構建Eureka客戶端

Eureka客戶端包含在Spring Cloud包中。為此,我們需要開發Eureka客戶端並在預設埠8080上執行它。

訪問Spring Initializer主頁https://start.spring.io/並下載帶有Eureka Client依賴項的Spring Boot專案。如下面的螢幕截圖所示:

Build Eureka Client

在主Spring Boot應用程式類檔案中下載專案後,我們需要新增@EnableEurekaClient註解。@EnableEurekaClient註解用於使您的Spring Boot應用程式充當Eureka客戶端。

主Spring Boot應用程式類檔案的程式碼如下所示:

package com.tutorialspoint.eurekaclient;

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

@SpringBootApplication
@EnableDiscoveryClient
public class EurekaclientApplication {
   public static void main(String[] args) {
      SpringApplication.run(EurekaclientApplication.class, args);
   }
}

確保在您的構建配置檔案中添加了Spring Cloud Eureka客戶端依賴項。

Maven使用者依賴項的程式碼如下所示:

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

Gradle使用者依賴項的程式碼如下所示:

compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')

完整的構建配置檔案如下所示:

Maven - pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.3.3</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>eurekaserver</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>eurekaserver</name>
   <description>Demo project for Spring Boot</description>
   <url/>
   <licenses>
      <license/>
   </licenses>
   <developers>
      <developer/>
   </developers>
   <scm>
      <connection/>
      <developerConnection/>
      <tag/>
      <url/>
   </scm>
   <properties>
      <java.version>21</java.version>
      <spring-cloud.version>2023.0.3</spring-cloud.version>
   </properties>
   <dependencies>
      <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>
   </dependencies>
   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</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>

Gradle – build.gradle

buildscript {
   ext {
      springBootVersion = '3.3.3'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 21

repositories {
   mavenCentral()
}
ext {
   springCloudVersion = '2023.0.3'
}
dependencies {
   compile('org.springframework.cloud:spring-cloud-starter-eureka-client')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
   imports {
      mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
   }
}

要將Spring Boot應用程式註冊到Eureka Server,我們需要在我們的application.properties檔案或application.yml檔案中新增以下配置,並在我們的配置中指定Eureka Server URL。

application.yml檔案的程式碼如下所示:

eureka:
   client:
      serviceUrl:
         defaultZone: https://:8761/eureka
      instance:
      preferIpAddress: true
spring:
   application:
      name: eurekaclient

application.properties檔案的程式碼如下所示:

eureka.client.serviceUrl.defaultZone  = https://:8761/eureka
eureka.client.instance.preferIpAddress = true
spring.application.name = eurekaclient

現在,在主Spring Boot應用程式中新增返回字串的Rest端點,並在構建配置檔案中新增Spring Boot Starter Web依賴項。觀察下面的程式碼:

package com.tutorialspoint.eurekaclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class EurekaclientApplication {

   public static void main(String[] args) {
      SpringApplication.run(EurekaclientApplication.class, args);
   }

   @GetMapping(value = "/")
   public String home() {
      return "Eureka Client application";
   }
}

編譯和執行

您可以建立一個可執行的JAR檔案,並使用以下Maven或Gradle命令執行Spring Boot應用程式:

對於Maven,您可以使用以下命令:

mvn clean install

“BUILD SUCCESS”之後,您可以在target目錄下找到JAR檔案。

對於Gradle,您可以使用以下命令:

gradle clean build

“BUILD SUCCESSFUL”之後,您可以在build/libs目錄下找到JAR檔案。

現在,使用如下所示的命令執行JAR檔案:

java –jar <JARFILE> 

現在,應用程式已在Tomcat埠8080上啟動,並且Eureka客戶端應用程式已註冊到Eureka Server,如下所示:

Standard Commons Logging discovery in action with spring-jcl: please remove commons-logging.jar from classpath in order to avoid potential conflicts

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

[32m :: Spring Boot :: [39m              [2m (v3.3.3)[0;39m

[2m2024-09-11T12:46:03.672+05:30[0;39m [32m INFO[0;39m [35m19164[0;39m [2m---[0;39m [2m[eurekaserver] [           main][0;39m [2m[0;39m[36mc.t.e.EurekaserverApplication           [0;39m [2m:[0;39m Starting EurekaserverApplication using Java 21.0.3 with PID 19164
...
[2m[0;39m[36mc.n.e.registry.AbstractInstanceRegistry [0;39m [2m:[0;39m Registered instance EUREKACLIENT/DESKTOP-DTHL8BI:eurekaclient with status UP (replication=false)
[2m2024-09-11T12:54:08.159+05:30[0;39m [32m INFO[0;39m [35m19164[0;39m [2m---[0;39m [2m[eurekaserver] [nio-8761-exec-3][0;39m [2m[0;39m[36mc.n.e.registry.AbstractInstanceRegistry [0;39m [2m:[0;39m Registered instance EUREKACLIENT/DESKTOP-DTHL8BI:eurekaclient with status UP (replication=true)

在您的Web瀏覽器中訪問URL https://:8761/,您可以看到Eureka客戶端應用程式已註冊到Eureka Server。

Eureka Client Application

現在在您的Web瀏覽器中訪問URL https://:8080/,檢視Rest端點輸出。

Eureka Client Application Output
廣告