1.1. 一、说明。
根据spring-cloud-consul-config官方文档
的说明,consul提供了一个Key/Value Store
就是键值对的存储。
可以用来存储我们的配置和其他元数据。
在consul中的配置会在"bootstrap"阶段加载到spring的运行环境中。
1.2. 二、在consul中创建配置。
1.2.1. 1、配置说明。
根据上面的spring-cloud-consul-config
文档,springcloud项目启动之后,
会去consul
找/config
目录下面的配置。
我项目的应用名是spring.application.name=myTestService
,
并且我启动的配置文件是dev,就是spring.profiles.active=dev
,那么这个项目启动之后会按照下面的顺序查找配置。
config/myTestService,dev/
config/myTestService/
config/application,dev/
config/application/
也就是项目启动之后,查找配置中某个key的值:
- 先找
consul
中config/myTestService,dev/
的配置值。 - 再找
consul
中config/myTestService/
的配置值。 - 再找
consul
中config/application,dev/
的配置值。 - 再找
consul
中config/application/
的配置值。
其中config/application
文件夹中的配置对所有注册到consul的服务都可用,config/myTestService
文件夹中的配置只是对服务"myTestService"可用。
1.2.2. 2、在consul中新建文件夹。
启动consul后,点击Key/Value
,然后点击create
如下:
在"Key or folder"中输入要创建的文件夹名字config/myTestService,dev/
,如果是要建文件夹要以斜线结尾。
1.2.3. 3、在文件夹config/myTestService,dev/中创建data。
点击Key/Value
,会看到刚刚创建的config
文件夹,点击config
会看到myTestService,dev
文件夹。
在右边点击create
创建。
输入“data”,以“data”为key创建一个文件。选择文件的格式为yaml格式,
内容我只写了一个name: name from consul "myTestService dev"
然后保存就行了。
以“data”为key是因为springcloud默认就是读取这个key的内容作为配置。
也可以使用spring.cloud.consul.config.data-key
配置这个key的名字。
1.2.4. 4、对比上面的操作,创建下面的配置。
- 再找
consul
中config/myTestService/
的配置值。 - 再找
consul
中config/application,dev/
的配置值。 - 再找
consul
中config/application/
的配置值。
1.3. 二、新建springcloud项目,测试配置。
1.3.1. 1、pom.xml依赖配置。
<!--web服务器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--服务健康检查-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--服务注册、发现-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!--分布式配置中心-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
1.3.2. 2、bootstrap.yml配置文件。
# 服务的端口
server:
port: 8080
# 服务的管理端口,就是/actuator/health等actuator使用的端口。
#一般不配置,默认跟随本服务的端口server.port就可以了。
#management:
# server:
# port: 4452
spring:
application:
# 服务名
name: myTestService
cloud:
consul:
host: localhost
port: 8500
config:
enabled: true
format: yaml
# prefix: configuration
# defaultContext: apps
# profileSeparator: '::'
1.3.3. 3、application.yml配置文件。
spring:
profiles:
active: dev
name: name from consul-demo1 "application.yml"
1.3.4. 4、测试代码。
@SpringBootApplication
@RestController
public class ConsulDemo1Application {
public static void main(String[] args) {
SpringApplication.run(ConsulDemo1Application.class, args);
}
@Value("${name}")
private String name;
@RequestMapping("/configName")
public String configs() {
return name;
}
}
运行程序后访问http://localhost:8080/configName
出现name from consul "myTestService dev"
表示配置中心生效
并且config/myTestService,dev/
的配置值是最优先的值。