Springcloud config 配置中心
Spring Cloud Config是一个单独的微服务模块,分为服务端和客户端,主要为微服务框架提供集中化的配置支持。
服务端一般可称为配置中心,用来连接配置仓库,并为客户端提供配置信息。客户端可以是微服务框架中的各个微服务应用,可以指定使用配置中心管理配置内容,在启动的时候读取远程git的配置加载到应用中,并将配置文件加载到本地文件系统。
一、Config 配置原理
二、Config 服务端
2.1 搭建配置中心
-
创建 Spring Boot 项目
添加依赖
-
创建git 仓库,准备配置文件
新建git仓库
配置文件
Config配置文件命名规则
/{application}/{profile}/{label}
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties关键字:
application:应用的名称
profile: 对应的环境,dev/test
label: 分支
- 搭建配置中心
application.yml
server:
port: 8070
spring:
application:
name: config
cloud:
config:
server:
git:
uri: https://github.com/xxx/config-test.git
# 强制拉取
# force-pull: true
username: github账号
password: github密码
# 仓库路径
search-paths: /
#git 默认分支选为 master分支
default-label: master
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka/
主程序
@SpringBootApplication
// Eureka 客户端注解
@EnableDiscoveryClient
// 配置中心注解
@EnableConfigServer
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
- 测试
三、Config客户端
- 导入依赖
<!--配置中心客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
- 启动文件bootstrap.properties
spring.application.name=config-client
eureka.client.service-url.defaultZone=http://localhost:8080/eureka/
spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.service-id=CONFIG
# 注册在总服务里面的,配置服务 地址
#spring.cloud.config.uri= http://localhost:8070
spring.cloud.config.name=config-client
# 远程仓库的分支
spring.cloud.config.label=master
# dev 开发环境配置文件 | test 测试环境 | pro 正式环境
# 和git里的文件名对应
spring.cloud.config.profile=dev
- 测试程序
@RestController
public class ConfigController {
@Value(value = "${env}")
private String env;
@GetMapping("/getenv")
public String test(){
System.out.println(env);
return env;
}
}
运行结果
git仓库中的配置文件config-client-dev.properties
driver-class-name= com.mysql.jdbc.Driver
database.password=123456
database.url=jdbc:mysql://localhost:3306/zxg?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false
database.username=root
env=dev
遇到问题
当所有的配置文件都没问题,而启动客户端的时候报错
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder ‘env’ in value “${env}”.
往上教程很多,都无法解决。
当springcloud使用版本为2020.0.1时,还需要导入依赖spring-cloud-starter-bootstrap