配置中心用来管理所有微服务的配置。
能干嘛- 集中管理配置文件
- 不同环境不同配置,动态化的配置更新,分环境部署,例如dev/test/prod/beta/…
- 运行期间动态调整配置,不再需要在每个服务部署的机器上编写配置文件,服务会向配置中心统一拉取配置自己的信息
- 当配置发生变动时,服务不需要重启即可感知到配置的变化并应用新的配置
- 将配置信息以REST接口的形式暴露
- 首先建立一个仓库,我这里使用gitee仓库
- 依赖
org.springframework.cloud spring-cloud-config-server
- 配置文件
server.port=6001 eureka.client.fetch-registry=true eureka.client.register-with-eureka=true eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka/ spring.application.name=cloud-config-center spring.cloud.config.server.git.uri=git@gitee.com:z2h/springcloud-config.git spring.cloud.config.server.git.search-paths=springcloud-config //仓库名 spring.cloud.config.label=master //分支
- 主启动类
@SpringBootApplication
@EnableConfigServer
public class ConfigCenterMain6001 {
public static void main(String[] args) {
SpringApplication.run(ConfigCenterMain6001.class, args);
}
}
EnableConfigServer注解不要忘了。
此时Config配置中心是从gitee读取文件。
- 依赖
org.springframework.cloud spring-cloud-starter-config
- 配置文件
//bootstrap.properties server.port=6501 eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka/ spring.application.name=config-client // 以下相当于配置访问文件的url:http://configcenter6001.com:6001/master/application-dev.properties spring.cloud.config.label=master spring.cloud.config.name=application spring.cloud.config.profile=dev spring.cloud.config.uri=http://configcenter6001.com:6001
- 主启动类
@EnableEurekaClient
@SpringBootApplication
public class ConfigClientMain6501 {
public static void main(String[] args) {
SpringApplication.run(ConfigClientMain6501.class, args);
}
}
Config客户端之动态刷新
此时存在一个问题,假设远程仓库中的文件进行了修改,config-client此时却并不知道,需要手动的重启微服务,因此需要动态刷新机制来解决这个问题。
- 依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator
- 配置文件
//暴露监控端点 management.endpoints.web.exposure.include=*
- 控制层
@RestController
@RefreshScope
public class ConfigCenterController {
@Value("${config.port}")
private String serverPort;
@GetMapping("/serverport")
public String getServerPort(){
return serverPort;
}
}
添加RefreshScope注释赋予刷新功能。
配置完上述后,需要手动发送post请求来进行配置的动态刷新:curl -X POST "http://localhost:6501/actuator/refresh"
虽然利用手动发送post请求能够实现动态刷新。假设有多态config-client,且有些需要动态更新有些不需要,那么每次都需要运维人员来给不同的client发送请求,这样就很麻烦。而Bus总线可以通过差异化广播的方式,解决这一问题。



