目录
1、bootstrap.properties优先于application.properties加载
在开始之前引用Spring Cloud 官方文档介绍一下,Spring Cloud 为开发人员提供了一套快速构建分布式系统的模块,包括分布式配置管理,服务注册发现,断路器,智能路由,微代理,控制总线,一次性令牌,全局锁,领导选举,分布式会话,集群状态等。主要特性包括:
分布式/版本配置
服务注册和发现
路由
服务 到 服务的调用
负载均衡
断路器
全局锁
领导班子的选举和
分布式消息
1、Spring Cloud 架构模块初览
注册中心
Eureka、Spring Cloud Zookeeper、Spring Cloud Consul、Spring Cloud etcd
配置中心
Spring Cloud Config(文件系统、git远程仓库、数据库)
负载均衡
Netflix Robbin、netflix Feign(基于Robbin实现)
断路器
Netflix Hystrix、Hystrix Dashboard(Hystrix各个节点的监控面板Web ui)
Api服务网关
Netflix Zuul
服务调用链路追踪
Spring Cloud Sleuth(日志收集端)、Zipkin(日志上报服务端)
2、Spring Cloud Bootstrap
1)、bootstrap.properties优先于application.properties加载
Spring Cloud是建立在Spring Boot之上的,当Spring Boot使用 SpringApplication 或者 SpringApplicationBuilder 进行构建的上下文时,默认是在maven项目的根目录下创建一个application.properties(或者yml)的配置文件,而Spring Cloud 的默认配置文件为跟目录下创建一个bootstrap.properties的配置文件。那么问题来了,他们的加载顺序是什么?
当项目启动的时候,bootstrap以parent的形式优先于application.properties进行加载。application.properties的加载器为org.springframework.boot.context.config.ConfigFileApplicationListener的实现了org.springframework.core.Ordered接口,而实现的排序接口返回的值为 Order = Orderd.HIGHEST_PRECEDENCE + 10,源码如下:
public class ConfigFileApplicationListener implements EnvironmentPostProcessor,
SmartApplicationListener, Ordered {
/**
* The default order for the processor.
*/
public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10;
private int order = DEFAULT_ORDER;
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
}
bootstrap的加载器为org.springframework.cloud.bootstrap.BootstrapApplicationListener也实现了org.springframework.core.Ordered 接口,之前的版本实现的排序Orderd=Orderd.HIGHEST_PRECEDENCE + 5。按照排序,实现的值越小越先进行加载,2.1.1版本源码如下:
public class BootstrapApplicationListener implements
ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
private int order = -2147483643;
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
}
2)、bootstrap.properties配置路径
默认的Spring Cloud会在maven根目录下查找bootstrap.properties(或者yml)的配置文件,可以配置该配置文件的路径和名称,如下:
# 配置文件的路径,默认为空,则默认查找根目录
spring.cloud.bootstrap.location = config
# 配置文件的名称,默认为 bootstrap,则默认加载该名称的文件
spring.cloud.bootstrap.name = spring-cloud
所以当Spring Cloud启动的时候会,加载spring.cloud.bootstrap.location目录下名为spring.cloud.bootstrap.name的配置文件。