配置不在需要和应用程序一起打包和部署。这样的话,配置的变更或回滚就在不需要重新构建和重新部署应用了。配置甚至可以在运行时进行变更,无需重启应用。
共享通用配置的微服务管理自己的属性设置副本,并且能够管理共享的相同属性。如果需要对属性进行变更只需要在一个地方执行一次就可以应用到所有的微服务上
SpringcloudconfigServer提供了中心化的配置功能,应用中的所有微服务均可以依赖该服务器来获取配置。因为它是中心化的,所以是一个一站式的配置商店,所有的服务都可以使用它,另外它还能够为特定服务提供专门的配置
1.构建Spring Cloud Config Server
1.1新建SpringBoot Config项目 导入依赖
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies>
1.2 启动类上添加@EnableConfigServer注解
@EnableDiscoveryClient @EnableConfigServer @SpringBootApplication public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
Config可以结合远程Git 仓库或 本地Git仓库拉取配置
2 结合Git仓库
2.1在Config Server中配置远程Git信息
spring: application: name: configServer cloud: config: server: git: #Git仓库账号密码 username: xxxxx password: xxxxx #分支 label: ap-devlop # 配置文件仓储的仓库路径 uri: https://XXXXXXXXX.git
2.2在Config Server中配置本地Git信息
直接放在resource文件夹下即可
spring: profiles: active: dev application: name: configServer #名称 cloud: config: server: native: search-locations: classpath:server-config-files/
3其他微服务拉取Config Server的配置文件
在微服务的yaml文件中配置
spring: application: name:server01 cloud: config: # 用于路径匹配,则匹配server01-config-dev配置文件 profile:config-dev #与注册在Eureka的ConfigServer Name相同 serviceId: configServer enabled: true # git分支 label: ap-devlop
在运行时刷新配置属性
可以分为手动和自动刷新,暂时只用到手动刷新,自动需结合Bus
手动刷新:
客户端启用一个特殊的"/actuator/refresh"端点,对每个服务的这个端点发送HTTP POST请求将会强制配置
客户端从
Config Server
的后端检索最新的配置url+端口号+/actuator/refresh(可直接在postman调用)