spring cloud配置中心示例
示例代码
server端:
管理所有项目的配置文件
client端
就是我们需要运行的项目,项目所有的配置文件放到配置中心内,启动时从server端读取配置
首先在git新建一个文件夹config-repo存放项目的配置文件:
myconfig-dev.properties
myconfig-pro.properties
分别配置
1 | hello=helloworld dev |
1 | hello=helloworld pro |
server端
添加依赖
新建一个springboot的maven项目,添加spring-cloud-config-server依赖
1
2
3
4
5<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
配置文件
application.properties配置:
1 | server.port=8888 |
启动类
启动类增加@EnableConfigServer注解
1 | import org.springframework.boot.SpringApplication; |
测试
启动server,访问:http://localhost:8888/myconfig/dev
返回:
1 | { |
正常读取到git中的myconfig-dev.properties配置文件
client端
添加依赖
1 | <dependency> |
配置文件
client读取server的配置放在bootstrap,properties中,此配置文件会在application.properties之前加载
application.properties:
1 | spring.application.name=spring-cloud-config-client |
bootstrap.proerties
1 | spring.cloud.config.uri=http://localhost:8888 |
spring.application.name:对应{application}部分
spring.cloud.config.profile:对应{profile}部分
spring.cloud.config.label:对应git的分支。如果配置中心使用的是本地存储,则该参数无用
spring.cloud.config.uri:配置中心server地址
测试
client端当前配置的是读取:myconfig-dev.properties
1 | hello=helloworld dev |
client端新建一个Controller代码:
1 |
|
启动client项目访问:http://localhost:8080/index
返回:helloworld dev
安全验证
配置中心任何人都能访问时不安全的,可以加一个安全验证
server
增加spring-boot-starter-security依赖:
1 | <dependency> |
配置文件配置用户名密码:
1 | pring.security.user.name=zhaoyundi |
现在访问:http://localhost:8888/myconfig/dev 就需要输入用户名密码了
client
bootstrap.properties增加
1 | spring.cloud.config.username=zhaoyundi |
配置完成
参考:
纯洁的微笑:配置中心git示例
spring-cloud-config reference documents