当一个系统中的配置文件发生改变的时候,我们需要重新启动该服务,才能使得新的配置文件生效,spring cloud config可以实现微服务中的所有系统的配置文件的统一管理,而且还可以实现当配置文件发生变化的时候,系统会自动更新获取新的配置。
yml 配置文件保存到 git 服务器,例如 github.com或 gitee.com
当然也不一定非要保存到git服务器, 保存到数据库, 或config项目中也是可以的, 不过官方推荐是保存到git服务器
微服务启动时,从服务器获取配置文件
例如有4个项目
各个项目都有自己的配置文件, 且配置了eureka注册中心
创建一个空项目, 然后把业务服务和zuul的配置文件等放入这个空项目, 并修改文件名, 例如:
item-service-dev.yml # 商品服务
user-service-dev.yml # 用户服务
order-service-dev.yml # 订单服务
zuul-dev.yml # zuul网关
然后清除这些项目中原有的配置文件, 注释或删掉都可以
注意, 配置文件优先级 [配置中心 > 项目启动参数 > 项目中原有的配置] 即如果项目中有配置文件, 配置中心也有配置文件, 配置中心的配置文件会覆盖项目中的配置文件, 如果我们不想覆盖, 只需要再配置中心指定的配置文件中填写如下配置信息即可
spring:
cloud:
config:
override-none: true # 开启不覆盖原有配置文件
可上传到gitee, github等服务器
config 配置中心从 git 下载所有配置文件。
而其他微服务启动时从 config 配置中心获取配置信息。
创建spring boot项目并导入如下依赖: config server
, eureka discovery client
<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>
application.yml
spring:
application:
name: config-server
# config主要配置
cloud:
config:
server:
git:
uri: https://github.com/你的个人路径/sp-config # 仓库路径
searchPaths: config # 子路径
# 如果你的不是共有仓库, 需要再配置如下信息
# username: your-username
# password: your-password
# 如果你的分支不是默认的master, 需要配置如下信息
# default-label: master # 分支
server:
port: 6001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
@EnableConfigServer // 开启config服务
// @EnableDiscoveryClient // eureka客户端, 高版本springboot可省略
@SpringBootApplication
public class Sp12ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(Sp12ConfigApplication.class, args);
}
}
启动顺序: 先启动注册中心, 再启动config配置服务
访问 item-service-dev.yml 可以使用以下形式:
如果显示了配置文件信息, 继续进行下面的操作
修改以下项目,从配置中心获取配置信息
config client
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
例如 item-service
# .. 应用名等配置
spring:
cloud:
config:
discovery:
enabled: true
service-id: config-server
name: item-service
profile: dev
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
配置好service和zuul服务等, 就可以了
启动顺序: 1.eureka注册中心 2.config配置服务 3.其他服务
原文:https://www.cnblogs.com/zpKang/p/13606923.html