spring cloud 分布式配置中心

配置仓库

本文使用码云git库,实际环境最好使用公司内部git服务。

demo仓库:https://gitee.com/wekri/spring-cloud-config-repo.git

创建config server

依赖:

1
2
3
4
dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>

启动方法加上@EnableConfigServer注解开启配置服务器的功能

1
2
3
4
5
6
7
8
9
@EnableConfigServer
@EnableDiscoveryClient
@SpringBootApplication
public class ConfigurationServiceApplication {

public static void main(String[] args) {
SpringApplication.run(ConfigurationServiceApplication.class, args);
}
}

项目配置文件:bootstrap.yml

  • config.label:使用仓库的分支
  • server.git.uri:配置git仓库地址
  • server.git.search-paths:
  • server.git.username:git仓库用户名
  • server.git.password:git仓库密码

注意:如果使用application.properties配置文件,{application}不需要加单引号,
如果使用bootstrap.yml配置文件,'{application}'需要加上单引号。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server:
port: 8080

spring:
application:
name: config-server
cloud:
config:
label: master
server:
git:
uri: https://gitee.com/wekri/spring-cloud-config-repo.git
search-paths: '{application}'
username:
password:

eureka:
client:
serviceUrl.defaultZone: http://www.wekri.com/eureka
instance:
hostname: localhost
instance-id: config-server

然后启动项目,就可以访问到配置了http://127.0.0.1:8080/config-client/dev

http请求地址和资源文件映射如下:

1
2
3
4
5
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

客户端使用

新建一个springboot项目:configuration-client

依赖

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>

配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server:
port: 8088

spring:
application:
name: config-client
profiles:
active: dev
cloud:
config:
profile: ${spring.profiles.active} #dev,test,staging,prod
discovery:
enabled: true # 默认false,设为true表示使用注册中心中的configserver配置而不自己配置configserver的uri
serviceId: config-server # 指定config server在服务发现中的serviceId,默认为:configserver
eureka:
client:
serviceUrl.defaultZone: http://www.wekri.com/eureka
instance:
hostname: localhost

启动项目,可以使用environment.getProperty("env")获取到相应的配置。

码云源码:查看


spring cloud 分布式配置中心
https://www.wekri.com/springcloud/springCloudConfig/
Author
Echo
Posted on
May 17, 2018
Licensed under