随着微服务数量增加,为了使生产、测试和运维等各环境能协调统一,即使在环境切换时不会因为微服务的数量而进行大量的修改配置,于是就出现了配置中心。
Config
作用
随着微服务数量的不断增多,为了使开发者可以管理不同环境(开发、测试、生产)下的配置,一个应用在环境迁移后有完整的配置使程序正常运行
开源配置中心
- 携程 Apllo
- 百度 Disconf
- 淘宝 Diamond
配置方式
- 本地文件系统
- SVN
- Git(默认方式)
Git配置仓库
1. 登录
github

当然,没有账号的需要申请一个
2. 创建仓库
完善仓库信息
创建好的仓库文档会显示客户端的相关操作命令
3. 下载安装客户端
下载路径
下载好后一直next安装就好,只不过需要注意的是安装路径选择英文路径
4. 连接仓库
启动**git-bash.exe**
//绑定用户
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
5. 关联git仓库
git remote add origin [email protected]:ring-finger/SpringCloud-Config.git
6. 操作命令
//把这个目录变成Git可以管理的仓库
git init
//添加
git add .
//提交日志
git commit -m "提交测试"
//提交文件
git push -u origin master
//更新文件
git push -u origin master
Config服务端
1. 创建一个 SpringBoot
项目,我这里命名为ConfigServer
SpringBoot
2. 在pom.xml文件中添加依赖
<!--config配置中心服务端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
3. 修改配置文件
server.port=8091
spring.application.name=config-server
#配置的git仓库的地址
spring.cloud.config.server.git.uri=https://github.com/ring-finger/SpringCloud-Config
# git仓库地址下的相对地址,可以配置多个,用,分割
spring.cloud.config.server.git.search-paths=
spring.cloud.config.server.git.username=ring-finger
spring.cloud.config.server.git.password=githubzw64
# 本地存储的配置方式,默认检索src/main/resource路径下
#spring.profiles.active=native
# 制定本地配置文件的路径
#spring.cloud.config.server.native.searchLocations=file:E:/properties/
4.添加注解 @EnableConfigServer
@EnableConfigServer
@EnableConfigServer//激活对配置中心的支持
@SpringBootApplication
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
Config客户端
1. 创建一个 SpringBoot
项目,我这里命名为ConfigClient
SpringBoot
2. 在pom.xml文件中添加依赖
<!--配置中心客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
3. 修改配置文件
bootstrap.xml
- springcloud config 的相关配置要放在bootstrap.xml才有效
- application.properties中添加项目名和端口配置
spring:
profiles: dev
cloud:
config:
uri: http://localhost:8091 # 配置中心的具体地址,即 config-server
label: master # 对应 {label} 部分,即 Git 的分支。如果配置中心使用的是本地存储,则该参数无用
profile: dev # 对应 {profile} 部分
name: config-client # 对应 {application} 部分
4. 获取配置参数
- github中参数格式
girl:
name: "格式故事"
age: 18
label: "master"
- 配置文件的对应实体类
@Data
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private String name;
private int age;
private String label;
}
- 读取配置文件
@RestController
public class ClientController {
@Autowired
private GirlProperties girlProperties;
@GetMapping("/hello")
public String getProperties(){
return girlProperties.toString();
}
}
连接测试
- 访问接口
,使用的是客户端的porthttp://localhost:8092/hello
SpringCloud搭建Config配置中心的客户端和服务端及配置仓库github的使用
服务化与高可用
- 服务化其实就是把配置中心
的服务端和客户端当作config
的客户端注册到eureka
的服务中eureka
- 高可用则是通过配置多个(一般两个)
的服务端,保证服务即使宕机时,仍有备用服务器提供支撑config
- 具体实现请参考之前写的
eureka
的配置
SpringCloud搭建Eurake注册中心、提供者和消费者代码示例
服务刷新
-
手动刷新的实现方式可以参考之前的文章
SpringCloud实现Config配置中心的手动刷新