0. 前提是已经配置好Consul,并启动
1. 添加必要依赖
<properties>
<java.version>11</java.version>
<!--声明 Spring Cloud 版本-->
<spring-cloud.version>2020.0.3</spring-cloud.version>
</properties>
<dependencies>
<!--Consul -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
</dependencies>
<!--Spring cloud-->
<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>
要注意一点:SpringCloud的版本必须要和SpringBoot相匹配,版本信息访问spring官网
2. 添加必要配置文件
server:
port: 8000
spring:
application:
name: secret-monitor
cloud:
consul:
host: localhost
port: 8500 # consul监听的端口
discovery:
serviceName: ${spring.application.name} # 注册到consul的服务名称
3. 在启动类中添加注解
@EnableDiscoveryClient
@SpringBootApplication
public class MainAppApplication {
public static void main(String[] args) {
SpringApplication.run(MainAppApplication.class, args);
}
}
启动服务,在consul的页面,就可以看到服务已经注册