Spring Cloud Config提供了分布式系统中配置功能的服务端与客户端支持。对于不同环境的应用程序它的服务端提供了一种中心化的配置管理方式。并且其不仅适用于Spring的应用程序,其它语言开发的程序同样能够使用(这点很重要)。
环境要求
- 首先需要安装
在输入工程名(这里是configuration-service)后选择下一步(Next),在依赖项中选中Config Server。

之后,点击Finish,即可完成工程的创建。
接着,在ConfigurationServiceApplication类上添加@EnableConfigServer注解。
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @EnableConfigServer @SpringBootApplication public class ConfigurationServiceApplication { public static void main(String[] args) { SpringApplication.run(ConfigurationServiceApplication.class, args); } }最后一步,在application.properties文件里配置可用的端口及用于保存服务端配置的仓库地址。
server.port=9555 #spring.profiles.active=native #spring.cloud.config.server.native.searchLocations=file:///${USERPROFILE}/Desktop/config spring.cloud.config.server.git.uri=file:///${USERPROFILE}/Desktop/configSpring Cloud Config中最常用的是git仓库,这种场景下通过对
spring.cloud.config.server.git.uri指定具体路径即可达成配置目的。
当然也可以不用git仓库,比如使用单纯的文件管理。
这时就需要同时使用spring.profiles.active=native及spring.cloud.config.server.native.searchLocations={配置文件目录路径}这两条配置项。做为例子,在
file:///${USERPROFILE}/Desktop/config目录下建立了一个application.properties文件,里面加入一条配置message=Hello World!。启动这个应用,一个Spring Cloud Server便产生了。
测试下其是否正常工作,可以在浏览器中输入
http://localhost:9555/application/dev地址查看。如果是类似下列的结果,说明是正常的。{"name":"application","profiles":["dev"],"label":null,"version":"c0f022755482d4a98f66dc19c8c4e0af512dc4f2","state":null,"propertySources":[{"name":"file:///C:\\Users\\Ken/Desktop/config/application.properties","source":{"message":"Hello World!"}}]}客户端
同样是选择新建Spring Starter Project。但这次在依赖项中选择Config Client。

完成创建后,再在pom.xml中追加两个依赖。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
