用 Consul 存储键值对,实现分布式配置中心,支持不需要重启配置中心服务就能读取更新后的属性。
在前面开发基础上,稍作调整,暂只调整日志服务。
1、在日志服务里添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
2、调整配置文件,移除端口号,最后两行不能少,否则报错
spring:
application:
name: logservice
profiles:
active: dev
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: logservice
config:
enabled: true
format: yaml
prefixes: config
defaultContext: application
profileSeparator: ','
data-key: data
config:
import: optional:consul:localhost:8500
3、在 Consul 管理页面添加键值对,
单击Key/value菜单,然后单击 create按钮,弹出如下页面:
需要填写两个地方,
第一个地方:key or folder文本框:
这个地方很关键,需要和配置文件中一致,这里写为:
config/application,dev/data
和配置文件里的几个地方一致:
prefixes: config
defaultContext: application
profileSeparator: ','
data-key: data
第二个地方,value部分,因为配置文件里设置格式为yaml,添加几个属性值如下:
server:
port: 8081
log:
test: hello
然后单击 save按钮保存,没问题的话会提示success! Your key has been saved。
4、启动日志服务,不报错,说明配置成功。
5、访问日志服务,http://localhost:8081/log,端口号已从配置中心读取生效。
6、在日志服务里添加一个API接口,
@Value("${log.test}")
String hello;
@GetMapping("/data")
public String data() {
return hello;
}
7、浏览器访问该接口,http://localhost:8081/data,返回hello,说明从配置中心读取成功。
8、通过在API接口的Controller类上添加如下注解,在属性配置更新后,不用重启配置服务就能生效。
@RefreshScope