加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

MSDS构建统一配置中心

(2017-03-31 18:15:40)
标签:

springboot

springcloud

配置中心

分类: 微服务

Spring Boot有一个非常重要的改变就是简化了配置,使用application.properties文件定义了很多默认配置

但是配置文件分开管理来还是比较麻烦的,而且环境越多配置约容易出问题。Spring Cloud提供了一种统一配置的方案:Spring Cloud Config Server。

Spring Cloud Config项目是一个解决分布式系统的配置管理方案。它包含了ClientServer两个部分。

Server端配置

Spring Cloud Config Server本质上也是一个Spring Boot的web项目,只需要添加对应的parent,然后加入相关的依赖就可以启动这个工程了。

Maven的pom.xml中需要添加以下内容:   


config server的resource目录下的application.properties:

server.port=8888 
spring.cloud.config.server.git.uri=file://Users/whthomas/config-repo

spring.application.name=configserver 
spring.cloud.config.uri=http://localhost:8888

启动项目的代码:

@SpringBootApplication 
@EnableConfigServer 
public class DemoApplication { 
public static void main(String[] args) { 
SpringApplication.run(DemoApplication.class, args); 
 
}

其实和一般的SpringBoot项目启动没有什么区别,只是多了一个@EnableConfigServer注解。

配置环境仓库( Environment Repository )

上面的application.properties中有一个

spring.cloud.config.server.git.uri=file://Users/whthomas/config-repo

这个配置指的项目配置仓库的位置,这个位置可以是:git文件夹svn文件夹或者github项目位置,任何能访问到文件的地方。

环境仓库(例子中的文件夹中)中提供环境配置对象配资源给Config Server发布给各个consumer使用。

环境资源的命名规则由以下的三个参数确定:

  • {application}映射到Config客户端的spring.application.name属性
  • {profile}映射到Config客户端的spring.profiles.active属性,可以用来区分环境,比如dev,test,produce等等
  • {label}映射到Git服务器的commit id,分支名称或者tag,默认值为master

仓库中的配置文件会被转换成web接口,访问可以参照以下的规则:

/{application}/{profile}[/{label}
/{application}-{profile}.yml
/{label}
/{application}-{profile}.yml 
/{application}-{profile}.properties 
/{label}/{application}-{profile}.properties

举个栗子:

我在配置中心的目录下放置文件:

  • cloud-config-rd.properties
  • cloud-config-dev.properties
  • cloud-config-test.properties
  • cloud-config-test.properties

cloud-config-rd.properties为例子,它的application是cloud-config,profile是rd.client会根据填写的参数来选择读取对应的配置。

那么接下去来看client端的处理。

Client端配置

创建一个普通的SpringBoot项目,pom.xml中加入Spring Cloud的配置。


pom.xml中的dependencies节点下添加


resource目录下的application.properties添加这样几个配置:

# 配置中心服务的地址 
spring.cloud.config.uri=localhost:8888 
# 要读取的配置文件application属性 
spring.cloud.config.name=cloud-config 
# 要读取的配置文件profile属性,默认是dev 
spring.cloud.config.profile=${config.profile:dev}

以上的几个配置也可以在命令行启动jar时填写。

以上配置完成之后,在远端配置中心的对应的配置就会加载到项目中,和本地使用application.properties配置中添加配置是几乎一样的效果,使用@Value注解的配置也可以顺利读取到对应的配置。

写在后面

初步感受了下Spring Cloud Config项目,感觉还是一个相对底层的解决方案,各个方面还是特别成熟,比如在线更新配置还需要client开启web hock才能实现,如果client不是一个web项目,那更新配置就瞎了。相比之下,我们的MSDS配置中心支持自动刷新,支持ZK、界面可视化管理,数据可以加密处理等。

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有