在本系列的上一篇文章中, 我们实践了如何搭建注册与发现服务,现在,我们要实践注册一个业务服务。
在这个实验中,我们使用基于 Spring Boot 构建的一个示例来充当一个已经开发好的业务分为,示例构建请参考 Spring Boot 构建Rest服务实验手册(一)
要是 Spring Boot 的应用作为 Spring Cloud 的一个可注册的服务,只需要简单的改变项目中以下三个地方:
添加依赖库
在项目的 pom.xml 文件中:
- 将项目的 parent 元素 spring-boot-starter-parent 的版本号改为: 2.0.5.RELEASE, 改完后的如下:
1 2 3 4 5 6
| <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath/> </parent>
|
- 添加如下的依赖库和依赖管理项:
1 2 3 4 5 6 7 8
| <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-actuator</artifactId> </dependency>
|
1 2 3 4 5 6 7 8 9 10 11
| <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
|
修改启动类
为 Spring Boot 应用的启动类加上 @EnableEurekaClient 注解,代码如下:
1 2 3 4 5 6 7 8
| @EnableEurekaClient @SpringBootApplication public class TodoServiceApplication {
public static void main(String[] args) { SpringApplication.run(TodoServiceApplication.class, args); } }
|
删除测试类
删除 test/java 目录中的测试类。
修改 application.yaml 配置文件
在项目的配置文件: application.yaml 中添加一下内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| spring: application: name: cloud-simple-service
eureka: instance: leaseRenewalIntervalInSeconds: 1 leaseExpirationDurationInSeconds: 2 client: serviceUrl: defaultZone: http://localhost:8761/eureka/ healthcheck: enabled: true lease: duration: 5
|
启动程序并验证
启动应用,并访问注册服务器,看当前应用是否已经完成注册:
下一步
在下一步 中,我们将实践一个 Spring Cloud 中的 Gateway。