统一配置中心概述
如果微服务架构中没有使用统一配置中心时,所存在的问题:
- 配置文件分散在各个项目里,不方便维护
- 配置内容安全与权限,实际开发中,开发人员是不知道线上环境的配置的
- 更新配置后,项目需要重启
Spring Cloud Config就是我们通常意义上的配置中心。Spring Cloud Config-把应用原本放在本地文件的配置抽取出来放在中心服务器,本质是配置信息从本地迁移到云端。从而能够提供更好的管理、发布能力。
Spring Cloud Config分服务端和客户端,服务端负责将git(svn)中存储的配置文件发布成REST接口,客户端可以从服务端REST接口获取配置。
在SpringCloud中我们使用config组件来作为统一配置中心:
Spring Cloud Config服务器的配置
使用Spring Starter Project快速创建一个Config Server项目。
1) 增加@EnableConfigServer注解
@SpringBootApplication
@EnableConfigServer
public class MyConfigServerApplication {
}
2) 配置application.yml文件,设置服务器端口号和配置文件Git仓库的链接
server:
port: 3344
spring:
application:
name: cloud-config
cloud:
config:
server:
git:
uri: git@github.com:zzyybs/microservicecloud-config.git #GitHub上面的git仓库名字
3) 启动Config服务器MyConfigServerApplication,在浏览器中输入http://localhost:8888/my-client/master,既可以验证Config服务器从Git存储库读到了配置文件。
{
"name": "my-client",
"profiles": ["master"],
"label": null,
"version": "9bace30e907ff34dc2ce377ceb7831278c856455",
"propertySources": [
{
"name": "https://git.oschina.net/gongxusheng/spring-config-demo.git
/my-sample-config/my-client.yml",
"source": {"my-config.appName": "my-app"}
}
]
}
Config服务器支持带多种形式的URL,读者可以尝试一下:
- 增加profile参数,http://localhost:8888/my-client/uat/master
- yml格式,http://localhost:8888/my-client.yml
- properties格式,http://localhost:8888/my-client.properties
Spring Cloud Config客户端的配置
1) 在bootstrap.yml中设置客户端名称spring.application.name和Config服务器的地址,注意spring.application.name要和配置文件名相符
spring:
cloud:
config:
name: microservicecloud-config-client #需要从github上读取的资源名称,注意没有yml后缀名
profile: dev #本次访问的配置项
label: master
uri: http://localhosts:3344 #本微服务启动后先去找3344号服务,通过SpringCloudConfig获取GitHub的服务地址
bootstrap.yml配置文件的优先级大于application.yml。
spring:
application:
name: microservicecloud-config-client
2) 主程序:
@SpringBootApplication
public class ConfigClient_3355_StartSpringCloudApp{
public static void main(String[] args){
SpringApplication.run(ConfigClient_3355_StartSpringCloudApp.class, args);
}
}
3)测试类
@RestController
public class ConfigClientRest
{
@Value("${spring.application.name}")
private String applicationName;
@Value("${eureka.client.service-url.defaultZone}")
private String eurekaServers;
@Value("${server.port}")
private String port;
@RequestMapping("/config")
public String getConfig()
{
String str = "applicationName: " + applicationName + "\t eurekaServers:" + eurekaServers + "\t port: " + port;
System.out.println("******str: " + str);
return "applicationName: " + applicationName + "\t eurekaServers:" + eurekaServers + "\t port: " + port;
}
}
githhub中的配置文件:
测试结果: