SpringCloud 项目使用了大量的SpringBoot项目,每个项目都有自己配置文件,这里使用config管理这些配置文件的内容
一、搭建config server
1、注入jar文件
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、配置 application.properties文件
#端口
server.port=8087
#serviceid
spring.application.name=configServer
#github的地址
spring.cloud.config.server.git.uri=https://github.com/shadowhulei/wxkk
3、启动类添加注解@EnableConfigServer
4、github 里创建文件时,文件命名规则可参考如下:
eg:要在master分支下创建一个properties文件,这个文件需要遵循
/{application}-{profile}.properties 或者 /{label}/{application}-{profile}.properties规则
如图:
这里提一下,在config-client客户端调用application-dev.properties时,需要注意:spring.application.name的值,就是“application-dev.properties”里的application;”spring.cloud.config.profile的值就是“application-dev.properties”里的dev;spring.cloud.config.label的值,就是“application-dev.properties”所在的分支位置master
5、访问config-server,测试读取配置文件信息
访问http://localhost:8087/application/dev,可看到如下返回结果:
关于http://localhost:8087/application/dev的访问路径,服务端启动后,可以看到如下信息,它指明了访问方式:
如访问http://localhost:8087/application-dev.properties,可看到如下结果
二、客户端配置
1、配置文件,必须使用bootstrap命名(后缀可以是 yml)
uri 执向了 config-service的服务路径,discovery.service指明了config-service-id的服务名称(id);spring.application.name必须是{application}-{profile}.properties 规则里的{application}内容。
2、添加jar包
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 动态刷新配置 更新了Git仓库中的配置文件,那如何让config-client能够及时感知到呢? 动态刷新配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3、使用注解@RefreshScope(动态刷新配置文件里的值)
三、测试刷新
1、修改github上的文件内容
2、使用postman 刷新config-client,http://localhost:8088/refresh(post请求)