在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库或svn中。在spring cloud config 组件中,分两个角色,一是config server,二是config client

config server
创建一个spring-boot项目,取名为config-server,添加依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.tmatesoft.svnkit</groupId>
<artifactId>svnkit</artifactId>
</dependency>

在主类上添加注解EnableConfigServer

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class ConfigServerApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ConfigServerApplication.class).web(true).run(args);
}
}

编写application.yml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server:
port: ${port:8081}
tomcat:
uri-encoding: UTF-8
spring:
application:
name: config-server
profiles:
active: subversion #使用svn必须设定成这个值
cloud:
enable: true
config:
server:
svn:
uri: http://192.168.0.1:8888/svn/service-configs/
username: xxx
password: xxx
basedir: D:/repo/ #仓库的本地地址,默认是虚拟目录,最好指定一个实体目录
#label: master #label是git标签,指分支,默认maser分支,svn默认值是trunk,是仓库地址下的trunk目录,测试更改无效
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8082/eureka/

配置中心很简单,就写个主类加个注解,剩下的就是配置了,上例中是将配置中心作为微服务注册到注册中心,这样可以实现高可用的分布式配置中心。

上面指定存放配置文件的svn地址是http://192.168.0.1:8888/svn/service-configs/,实际配置文件需要放在service-configs/trunk/文件夹下。

config client

还是以sample为例,添加boostrap.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
spring:
profiles:
active: dev
application:
name: sample
cloud:
config:
discovery:
enabled: true
serviceId: config-server
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8082/eureka/

指定profile为dev,指定程序名为sample,指定配置服务id为config-server,这样sample就会请求配置中心加载sample-dev.yml的配置文件。

因为profile、application.name和eureka配置已经在bootstrap.yml指定了,就不需要在application.yml中重复指定。

配置使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Controller
@RequestMapping("/")
@RefreshScope
public class TestController {
@Value("${name}")
private String desc;
@ResponseBody
@RequestMapping("param")
public Object test(HttpServletRequest request){
Map params = HttpServletUtil.getRequestParameters(request);
params.put("msg","请求成功");
params.put("desc",desc);
return params;
}
}

在TestController添加注解@RefreshScope,添加一个局部变量desc,该值从配置文件获取。新建一个sample-dev.yml文件

1
name: 这是描述1

上传到svn,项sample服务发送POST请求localhost:8084/refresh,localhost:8084地址是sample服务运行的真实地址,如果有运行多个sample服务,需要对每一个sample服务POST一次refresh请求。refresh成功后,请求param接口,发现desc字段的值变成’这是描述1’,每一次修改sample-dev.yml文件后,都需要提交到svn,然后refresh sample服务。