Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持。使用Config Server,您可以在所有环境中管理应用程序的外部属性。客户端和服务器上的概念映射与Spring
Environment
和PropertySource
抽象相同,因此它们与Spring应用程序非常契合,但可以与任何以任何语言运行的应用程序一起使用。随着应用程序通过从开发人员到测试和生产的部署流程,您可以管理这些环境之间的配置,并确定应用程序具有迁移时需要运行的一切。服务器存储后端的默认实现使用git,因此它轻松支持标签版本的配置环境,以及可以访问用于管理内容的各种工具。可以轻松添加替代实现,并使用Spring配置将其插入.
spring_cloud_config_server
新建一个最简单的springboot项目,命名为 spring_cloud_config_server_demo.
在项目的启动程序上添加开启配置中心的注解 @EnableConfigServer,在 application.yml 配置文件中可以配置服务的端口和配置中心的地址.
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/Haiyoung/spring_cloud_config_center.git
spring_cloud_config_center
新建git仓库 spring_cloud_config_center,在仓库的根目录下新建文件 my-config.yml,文件内容如下:
test:
name: haiyoung001
city: shanghai
启动 spring_cloud_config_server
运行 SpringCloudConfigServerDemoApplication,启动配置服务,浏览器中访问
http://localhost:8888/my-config/master,返回结果如下所示:
{
"name":"my-config",
"profiles":[
"master"
],
"label":null,
"version":"702f63a715c1875b25d94edbcbec50a3fe47e799",
"state":null,
"propertySources":[
{
"name":"https://github.com/Haiyoung/spring_cloud_config_center.git/my-config.yml",
"source":{
"test.name":"haiyoung",
"test.city":"shanghai"
}
}
]
}
可见,配置服务启动成功。
spring_cloud_config_client
新启一个最简单的springboot项目,命名为 spring_cloud_config_client_demo.
在 resources 目录下新建配置文件 bootstrap.yml,配置内容如下:
spring:
application:
name: my-config #要访问的配置文件
cloud:
config:
uri: http://localhost:8888 #配置服务中心地址
server:
port: 8080
servlet:
context-path: /config_client #自定义应用上下文
新建测试类 ConfigController:
/**
* Created by Haiyoung on 2018/5/6.
*/
@RestController
public class ConfigController {
@Value("${test.name}") //获取配置中的属性 name
private String name;
@Value("${test.city}") //获取配置中的属性 city
private String city;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String helloSpringCloudConfig(){
return "Hello SpringCloudConfig, name is "+name+", city is "+ city +".";
}
}
运行 SpringCloudConfigClientDemoApplication,启动应用,浏览器中访问
http://localhost:8080/config_client/,返回如下所示:
Hello SpringCloudConfig, name is haiyoung, city is shanghai.
可见远程配置中心搭建成功,实现了最基本的功能。