在微服务架构中,可能会有成百上千个服务模块,如果每个模块对应都有一个配置文件,那么单纯维护不同环境(生产、测试、开发)每个模块的配置都是一件很痛苦的事情。假如有一个中心模块对应有一个配置文件,这个模块由于业务访问量相当大,横向扩展20个实例,那么可能会有20个配置文件(如果实例不在一台机器上),现在由于业务变动修改一个参数,那么必须去找到这20台服务上的配置进行修改,再将模块重启。这是费时又易错的过程。如何解决这样的问题呢,在这个微服务盛行的时代,Spring Cloud Config给出了很完善的解决方案。
本章主要包括的内容有:
看图说原理,从原理图来看。这个架构实现需要四部分:
构建出前面三部分,便可以解决在前言中抛出的大部分问题。
对于熟悉Spring Boot的使用者来讲,构建配置服务中心是很简单的事情,只需要完成以下步骤便可以是项目成为配置服务中心。
org.springframework.cloud
spring-cloud-config-server
@SpringBootApplication
@EnableConfigServer //添加ConfigServer注入
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
## 配置中心名称
spring.config.name=configserver
## 是否开启配置中心服务
spring.cloud.config.enabled=true
## 拉取配置的仓库地址(支持GIT、SVN、默认GIT)
spring.cloud.config.server.git.uri=http://yourGitAddress/root/springcloudconfig.git
## 仓库路径
spring.cloud.config.server.git.search-paths=config-repo
## 指定分支
spring.cloud.config.label=master
## 仓库账号
spring.cloud.config.server.git.username=you/git/username
## 仓库密码
spring.cloud.config.server.git.password=you/git/password
## 已经将仓库中config-repo路径下的test-test.properties拉取过来
Adding property source: file:/C:/系统路径//config-repo/test-test.properties
最终目的是让对应的业务模考启动后拉取不同的环境下(生产、测试、开发)的配置文件,即如何让业务模块成为一个自动拉取配置的客户端。
org.springframework.cloud
spring-cloud-config-client
spring:
application:
name: test ## 指定了配置文件的应用名,作为配置文件的名称
cloud:
config:
uri: http://localhost:8081/ ## 指定配置中心的的uri
profile: test ## 指定的环境 如果这样指定,会自动拉取test-test.properties文件
label: master ## 指定分支
server:
port: 7002
## 说明读取配置文件成功
Located property source: CompositePropertySource {name='configService',
propertySources=[MapPropertySource {name='configClient'}, MapPropertySource
{name='http://仓库路径/config-repo/test-test.properties'}]}
显然,即使一个模块成为了配置客户端,当仓库的配置文件发生改变,服务器端拉取到新的配置文件,客户端也无法在更新配置。为了解决这个问题,需要引进Spring Cloud Config Actuator监控模块,该模块提供了一系列API对模块进行监控。包括调用刷新接口让模块重新读取配置。
org.springframework.boot
spring-boot-starter-actuator
management:
endpoints:
web:
exposure:
include: "*"
curl -X POST "http://配置客户端服务ip:port/actuator/refresh"
通过前面一些列操作,似乎解决了前言抛出的90%的问题,但仍然有一个问题没有解决,当微服务模块达到成百上千的数量时,怎么样轻松同步各个模块的配置,显然Spring Cloud家族也考虑到这个问题。Spring Cloud Config Bus便可以解决这样的问题。后续在介绍其他组件的时候会对其做重点描述。因为这里面还涉及到高级消息队列的部署,这不是本章的重点。不做过多介绍。