在微服务架构中,服务注册与发现是一个非常重要的功能。Eureka作为Netflix开源的一款服务注册中心,为我们提供了方便快捷的服务注册与发现解决方案。本篇博客将介绍如何搭建Eureka Server,并将User Service注册到Eureka Server中。
准备工作
在开始之前,需要确保以下环境已经准备好:
- JDK 8及以上版本
- Maven 3.x
- IDE(推荐使用IntelliJ IDEA)
搭建Eureka Server
- 创建一个基于Spring Boot的项目,命名为
eureka-server。 - 在
pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 在
application.properties文件中添加以下配置:
spring.application.name=eureka-server
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.server.enable-self-preservation=false
- 创建一个
EurekaServerApplication类,并添加@EnableEurekaServer注解,启动Eureka Server:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
- 在IDE中运行
EurekaServerApplication类,访问http://localhost:8761,可以看到Eureka Server的控制台页面。
注册User Service到Eureka Server
- 创建一个基于Spring Boot的项目,命名为
user-service。 - 在
pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 在
application.properties文件中添加以下配置:
spring.application.name=user-service
server.port=8080
eureka.client.service-url.defaultZone=http://localhost:8761/eureka
- 创建一个
UserController类,并添加@RestController注解,定义一个/users接口:
@RestController
public class UserController {
@GetMapping("/users")
public List<String> getUsers() {
return Arrays.asList("User1", "User2", "User3");
}
}
- 在
UserServiceApplication类上添加@EnableDiscoveryClient注解,启动User Service:
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
- 在IDE中运行
UserServiceApplication类,然后访问http://localhost:8080/users,可以看到返回的用户列表。 - 再次访问Eureka Server的控制台页面
http://localhost:8761,可以看到User Service已成功注册到Eureka Server中。
总结
通过上述步骤,我们成功搭建了Eureka Server,并将User Service注册到了Eureka Server中。Eureka的服务注册与发现功能为我们的微服务架构提供了便利,帮助我们实现了服务的自动化管理。希望本篇博客对您有所帮助,感谢您的阅读!
本文来自极简博客,作者:技术探索者,转载请注明原文链接:Eureka学习:搭建Eureka Server、将User Service注册到Eureka Server中
微信扫一扫,打赏作者吧~