文章目录
1. 概述
解决痛点: 每一个微服务自带全局配置文件application.properties或者application.yml,如果越来越多的微服务,更改配置文件是比较麻烦的一件事情,所以Config Server组件的作用是把微服务所有配置文件统一的放置在一个云仓库(码云、Github)上,从云仓库取各自微服务的配置信息即可。更改文件的配置信息也非常方便
每个微服务获取配置文件的流程图
2. 使用
步骤1 - 添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
步骤2 - 配置文件application.yml
server:
port: 6060
eureka:
client:
#将自身联系信息注册到中介里面
service-url:
defaultZone: http://127.0.0.1:1111/eureka/
management:
info:
git:
enabled: true
spring:
application:
name: configServer
cloud:
config:
server:
git:
# 码云、Github的账号、密码
username: xxxxx
password: xxxxx
# 配置文件仓储的仓库路径
uri: https://gitee.com/changenen/congfig_server.git
timeout: 60
# 从仓库哪个分支进行获取微服务的配置文件 - 默认分支,微服务可以指定其他分支
default-label: master
inetutils:
timeout-seconds: 60
步骤3 - 启动类添加注解@EnableConfigServer@EnableEurekaClient
@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
步骤4 - 测试通过Config能否获取到云仓库的文件信息
码云仓库的文件信息
Config访问获取仓库的信息
步骤5 - 将Config_server与微服务进行整合,微服务从Config_server进行获取配置文件
Product_Service添加一个依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
注意:项目启动时,优先加载bootstrap.yml文件,然后在加载application.yml文件
Product的配置文件 - bootstrap.yml
eureka:
client:
#将可用区映射到与eureka服务器通信的完全限定URL列表
service-url:
defaultZone: http://127.0.0.1:1111/eureka/
spring:
application:
name: productService
cloud:
config:
discovery:
service-id: configServer
enabled: true
# 用于路径匹配的
profile: test
# 云仓库分支,不设置则使用config_server设置的分支
label: master
步骤6 - 测试Product_Service项目是否启动成功 - 因为数据库的信息放在云仓库上。如果获取到云仓库的信息,则能连接数据库