对于单体应用架构来讲,会使用配置文件管理咱们的配置,这就是以前项目中的application.properties或application.yml。若是须要在多环境下使用,传统的作法是复制这些文件命名为application-xxx.properties,而且在启动时配置spring.profiles.active={profile}来指定环境。java
在微服务架构下咱们可能会有不少的微服务,因此要求的不仅是在各自微服务中进行配置,咱们须要将全部的配置放在统一平台上进行操做,不一样的环境进行不一样的配置,运行期间动态调整参数等等。总之一句话,使用集中管理配置是颇有必要的。git
源码github
所有SpringCloud教程spring
可基于以前SpringCloudDemo项目改造,也能够建立为新的项目bootstrap
1、在GitHub建立一个git仓库用来存放git配置安全
{application}-{profile}.properties并将配置项粘贴到新建的文件中,如:建立zuul-dev.properties,并将原来的zuul模块中的application.properties所有配置粘贴进来
2、 建立config server端服务器
建立maven项目,可在原项目中建立Module架构
引入pom依赖app
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
建立启动类maven
package cn.kxtop.blog.configserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.config.server.EnableConfigServer; // 注入到Eureka中,使高可用 @EnableDiscoveryClient @SpringBootApplication @EnableConfigServer public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class); } }
配置配置文件application.properties
server.port=9999 # 配置git仓库的地址(修改成你本身的git仓库地址) spring.cloud.config.server.git.uri=https://github.com/qupengkun/spring-cloud-config-repo.git # git仓库帐号 spring.cloud.config.server.git.username=YOU_NAME # git仓库秘密 spring.cloud.config.server.git.password=YOU_PASSWORD #eureka,确保Spring cloud config 高可用 eureka.client.serviceUrl.defaultZone = http://localhost:8761/eureka/
启动项目并访问测试
http请求localhost:9999/zuul/dev
3、建立config client端
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-client</artifactId> </dependency>
#对应以前git仓库的文件名,如zuul-dev.properties spring.application.name=zuul #config server 地址 spring.cloud.config.uri=http://localhost:9999 #{profile}名(环境) spring.cloud.config.profile=dev #{label}名,git仓库分支 spring.cloud.config.label=master
以上基本演示了Spring Cloud Config的用法,仍是比较简单的,咱们引入了Eureka使Config Server能保证高可用,还能够增长@RefreshScope手动刷新配置文件,若是配置对安全要求较高,也能够引入JCE(Java Cryptography Extension)进行加解密操做。
其实每次都去手动刷新配置仍是比较麻烦且有很大的局限性的,那么如何修改配置后自动感知并刷新呢?请关注下一章基于Spring Cloud Bus实现自动刷新配置。
持续学习,记录点滴。更多文章请访问 文章首发