目标
实践 SpringCloud 中的配置管理,使用git管理方式,创建一个 config server,读取git的配置,创建一个普通应用,从 config server 获取配置信息。
步骤
(1)创建 git 仓库,上传配置文件
我在 gitee.com 上创建了一个仓库,新建目录 config-repo,并上传2个配置文件:
cfgtest-dev.properties
from=git-dev-1
cfgtest.properties
from=git-default-1
(2)创建 config server
创建一个springboot项目,依赖参考下面的配置:
org.springframework.cloud
spring-cloud-config-server
org.springframework.boot
spring-boot-starter-test
test
com.fasterxml.jackson.core
jackson-databind
2.9.6
com.fasterxml.jackson.core
jackson-core
2.9.6
com.fasterxml.jackson.core
jackson-annotations
2.9.6
application.properties 中添加配置信息:
spring.application.name=config-server
server.port=7001
spring.cloud.config.server.git.uri=https://gitee.com/land/springcloud-config
spring.cloud.config.server.git.searchPaths=config-repo
[email protected]
spring.cloud.config.server.git.password=123456
启动类上加注解 @EnableConfigServer
启动应用:
$ mvn spring-boot:run
验证一下,访问:
http://localhost:7001/cfgtest/dev/master
返回结果:
{
name: "cfgtest",
profiles: [
"dev"
],
label: "master",
version: "22810d6bf7ca1f7ab46efb03ee775ecaa3a720d6",
state: null,
propertySources: [{
name: "https://gitee.com/iriniland/springcloud-config/config-repo/cfgtest-dev.properties",
source: {
from: "git-dev-1"
}
},
{
name: "https://gitee.com/iriniland/springcloud-config/config-repo/cfgtest.properties",
source: {
from: "git-default-1"
}
}
]
}
(3)创建 config client
创建一个springboot项目,需要依赖:
org.springframework.cloud
spring-cloud-starter-config
org.springframework.boot
spring-boot-starter-web
创建 bootstrap.properties
spring.application.name=cfgtest
server.port=7002
spring.cloud.config.profile=dev
spring.cloud.config.label=master
spring.cloud.config.uri=http://localhost:7001/
创建一个测试controller:
@RestController
public class TestController {
@Value("${from}")
private String hello;
@RequestMapping("/hello")
public String from() {
return this.hello;
}
}
启动应用,访问:
http://localhost:7002/hello
返回结果:
git-dev-1
config server 要点总结
(1)创建git仓库,提交配置文件
(2)application.properties 配置
# git 地址
spring.cloud.config.server.git.uri
# git 地址下搜索的目录
spring.cloud.config.server.git.searchPaths=config-repo
# git 用户名
spring.cloud.config.server.git.username
# git 密码
spring.cloud.config.server.git.password
(3)启动类中添加注解 @EnableConfigServer
启动应用后就可以访问配置信息了,访问规则:
/应用名/环境名/分支名
例如:
http://localhost:7001/cfgtest/dev/master
config client 要点总结
最重要的一点:config server 的配置要放在 bootstrap.properties
中,因为 config 启动早于 application.properties
的加载,所以如果放在 application.properties 中的话就无法连接到 config server 了。