一、使用Git 作为配置中心
创建配置中心仓库, 用于存放配置文件。 先创建文件夹: config-repo作为配置存放仓库,包含以下文件
application-config-dev.ymlapplication-config-prod.ymlapplication-config-test.yml
文件包含的内容
env:name: dev #prod 或 test
1.1 创建Config-Server 服务端
- 创建项目 config-server-git
依赖
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-config-server</artifactId></dependency>
配置 ```yaml server: port: 8888
management: endpoints: health: show-details: always web: exposure: include: ‘*’ spring: cloud: consul: discovery: prefer-ip-address: true host: ‘localhost’ port: 8500
#本地存储配置的方式# 1.设置属性spring.profiles.active=native, Config Server会默认从应用的src/main/resource目录下检索配置文件# 2. 也可以通过spring.cloud.config.server.native.searchLocations=file:E:/properties/属性来指定配置文件的位置config:server:git:
uri: https://github.com/h-dj/SpringCloud-Learning/ # 配置git仓库的地址
search-paths: config-repo # git仓库地址下的相对地址,可以配置多个,用,分割。
username: # git仓库的账号
password:
uri: file:///home/hdj/IdeaProjects/config-repo
- 添加注解```java@EnableConfigServer@SpringBootApplicationpublic class ConfigServerGitApplication {public static void main(String[] args) {SpringApplication.run(ConfigServerGitApplication.class, args);}}
- 启动测试
- 先本地启动consul 注册中心
- 再启动配置中心访问 http://localhost:8888/application-config/dev

1.2 配置仓库中的配置文件转换为web接口规则
- 如配置文件: application-config-dev.yml
- application: application-config
- profile: dev
访问的地址为: /application-config/dev
/{application}/{profile}[/{label}]/{application}-{profile}.yml/{label}/{application}-{profile}.yml/{application}-{profile}.properties/{label}/{application}-{profile}.properties
1.3 Config-Clients 客户端
配置加载优先:
配置中心的配置文件 > 项目内bootstrap.properties > 项目内application.properties
- 创建项目config-client-git
依赖
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId></dependency>
配置bootstrap.yml
spring:application:name: config-clientcloud:config:discovery:#spring.cloud.config.uri=http://localhost:8888#使用服务发现的方式enabled: trueservice-id: config-serviceconsul:discovery:prefer-ip-address: truehost: localhostport: 8500
application.yml ```yaml server: port: 8989
management: endpoints: health: show-details: always web: exposure: include: ‘*’
order: discount: 100
- file:///home/hdj/IdeaProjects/config-repo 仓库的application.yml```yamlorder:discount: 60
属性配置
@ConfigurationProperties("order")@RefreshScope //刷新当前绑定的属性@Data@Componentpublic class OrderProperties {private Integer discount = 100;}
使用
@RestControllerpublic class ConfigController {@AutowiredOrderProperties orderProperties;@GetMapping("/getConfig")public String get() {return "折扣:" + orderProperties.getDiscount();}}
启动测试
- 本地先启动consul 注册中心
- 再启动config-server-git 配置中心服务端
- 然后启动 config-client-git 客户端
```shell
访问
http://192.168.43.122:8989/getConfig响应
60
修改config-repo 仓库的application.yml 的discount:50
刷新
curl -XPOST http://192.168.43.122:8989/actuator/refresh [“order.discount”]
再访问
http://192.168.43.122:8989/getConfig
响应
50 ```
