SpringCloud Config
统一配置中心学习笔记
在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库中。在spring cloud config 组件中,分两个角色,一是config server,二是config client。
Config Server是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置,默认使用Git存储配置文件内容,也可以使用SVN存储,或者是本地文件存储。
Config Client是Config Server的客户端,用于操作存储在Config Server中的配置内容。微服务在启动时会请求Config Server获取配置文件的内容,请求到后再启动容器。
使用的理由:
1.不方便维护
多人同时对配置文件进行修改,冲突不断,很难维护
2.配置内容安全和权限
主要是针对线上的配置来说,一般不对开发公开,只有运维有权限所以需要将配置文件隔离,不放到项目代码里
3.更新配置项目需要重启
每次更新配置文件都需要重启项目,很耗时。使用了配置中心后,即可实现配置实时更新(需配合springcloud-BUS)
配置服务端:
1. 将配置文件提交到码云
- 上传配置文件,将
eureka_service
模块的application.yml
改名为eurekaService-dev.yml
后上传
上传成功后可以在线修改或者等等操作;
文件命名规则:
{application}-{profile}.yml或{application}-{profile}.properties
application为应用名称 profile指的开发环境(用于区分开发环境,测试环境、生产环境等)
2. 创建模块 demo-config
并引入依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
3. 创建包和启动类: 并加上 @EnableConfigServer 注解,开启配置服务
@SpringBootApplication
@EnableConfigServer //开启配置服务
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
4. 编写配置文件application.yml
spring:
application:
name: demo-config
cloud:
config:
server:
git:
uri: https://gitee.com/chuanzhiliubei/tensquare-config.git
#username: xxx 私有仓库需配
#password: xxx
server:
port: 12000
5.启动模块 访问http://localhost:12000/eurekaService-dev.yml 可以看到配置文件内容为配置成功
配置客户端:
1. 在eureka_service模块上添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2. 添加bootstrap.yml
(名称固定值) ,删除application.yml
spring:
cloud:
config:
name: service #name和云端名称有关name+profile=配置文件名称: 例如:码云的文件名为service-dev.yml
profile: dev
label: master #拿云端上的那个分支
uri: http://127.0.0.1:12000 #集中式配置工程地址(demo-config模块的地址)
3. 启动工程模块demo-config
和 eureka_service
看看eureka_service
模块是否正常启动(如果正常启动并能访问到管理界面说明配置成功)
扩展资料:
配合rabbitMQ和springcloud-BUS 实现不用重启更新配置文件生效: https://segmentfault.com/a/1190000018910010