Spring Cloud Config是一个集中化外部配置的分布式系统,有服务端和客户端组成。它不依赖于注册中心,是一个独立的配置中心,支持多种存储配置信息的形式。下面以git为例~
客户端启动时会向服务端发起请求,服务端接收到客户端的请求后,根据配置的仓库地址,将git上面的文件克隆到本地的一个临时目录,然后服务端再读取本地文件返回给客户端。好处是,当git服务器故障或网络请求异常时,保证服务端仍可以正常工作。
创建工程config-server,pom中添加以下依赖:
4.0.0
iwhale
config-server
0.0.1-SNAPSHOT
config-server
Demo project for Spring Boot
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-parent
1.5.13.RELEASE
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-config-server
org.springframework.cloud
spring-cloud-dependencies
Edgware.SR3
pom
import
org.springframework.boot
spring-boot-maven-plugin
创建启动类,添加Config的注解
@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
application.yml配置文件如下:
server:
port: 9885
#context-path: /${spring.application.name}
#############################spring配置#############################
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://github.com/你的github名/Config-File.git
username: XXX
password: XXX
search-paths: file
search-paths属性可以搜索指定目录下的配置文件,下面在github上创建名为Config-File的仓库,创建文件夹file,文件夹下创建三个文件分别为config-info-dev.yml、config-info-prod.yml、config-info-test.yml,dev内容如下:其他两文件把dev改成test和prod而已。
cn:
springcloud:
book:
config: I am the git configuration file from dev environment.
name: hoooooo!
测试:启动服务,访问http://localhost:9885/config-info/dev/master,得到如下内容:
并且控制台打印出
客户端在https://blog.csdn.net/hjy132/article/details/84948047的zuul-web上添加,在pom中添加config-client依赖
org.springframework.cloud
spring-cloud-config-client
创建实体类ConfigInfoProperties,用于注入远程配置信息,添加注解@Component作为一个组件,同时使用@ConfigurationProperties加载配置属性,指定配置前缀
@Component
@ConfigurationProperties(prefix = "cn.springcloud.book")
public class ConfigInfoProperties {
private String config;
private String name;
//...省略get和set方法
}
创建ConfigController类,用于返回git上的配置信息
@RestController
public class ConfigController {
@Autowired
private ConfigInfoProperties configInfoValue;
@RequestMapping("/getConfigInfo")
public String getConfigInfo(){
return configInfoValue.getConfig()+" Hi! "+configInfoValue.getName();
}
}
再创建一个bootstrap.yml文件,该文件会优先于application.yml文件加载,因此会去加载远程的配置信息
spring:
cloud:
config:
label: master #指定请求分支
uri: http://localhost:9885 #请求config-server地址
name: config-info #请求远程文件名,多个用逗号隔开
profile: dev
测试,访问http://localhost:9884/getConfigInfo,得到