在本章中,将详细了解如何将Spring Boot Micro服务应用程序注册到Eureka Server中。在注册应用程序之前,请确保Eureka Server在端口8761上运行或首先构建Eureka Server并运行它。有关构建Eureka服务器的更多信息,请参阅上一章节。
首先,需要在构建配置文件中添加以下依赖项,以便向Eureka服务器注册微服务。
Maven用户可以将以下依赖项添加到pom.xml 文件中 -
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
现在,在主Spring Boot应用程序类文件中添加@EnableEurekaClient注解。@EnableEurekaClient注解用于指示Spring Boot应用程序充当Eureka客户端。
Spring Boot主应用程序如下所示 -
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class EurekaclientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaclientApplication.class, args);
}
}
要将Spring Boot应用程序注册到Eureka Server,需要在application.properties 文件或application.yml 文件中添加以下配置,并在配置中指定Eureka Server URL。
application.properties 文件的代码如下 -
eureka.client.serviceUrl.defaultZone = http://localhost:8761/eureka
eureka.client.instance.preferIpAddress = true
spring.application.name = eurekaclient
application.yml 文件的代码如下 -
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka
instance:
preferIpAddress: true
spring:
application:
name: eurekaclient
现在,添加Rest Endpoint以在Spring Boot应用程序中返回String,并在构建配置文件中返回Spring Boot Starter Web依赖项。如下给出的代码 -
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class EurekaclientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaclientApplication.class, args);
}
@RequestMapping(value = "/")
public String home() {
return "Eureka Client application";
}
}
现在,使用如下所示的命令运行JAR文件 -
java –jar <JARFILE>
在Web浏览器访问URL => http://localhost:8761/ ,看到Eureka Client应用程序已在Eureka Server中注册。
现在,在Web浏览器访问URL => http://localhost:8080/ ,然后查看Rest端点的输出。