Spring Boot系列(四) Spring Cloud 之 Config Client

Config 是通过 PropertySource 提供. 这节的内容主要是探讨配置, 特别是 PropertySource 的加载机制.

Spring Cloud 技术体系

  • 分布式配置
  • 服务注册/发现
  • 路由
  • 服务调用
  • 负载均衡
  • 短路保护
  • 分布式消息

Spring 事件机制

设计模式

  • 观察者模式(发布/订阅)

API: java.util.Observable , java.util.Observer

发布者通过 observable.notifyObservers() 通知, 订阅者是被动感知的. 这种模式是推模式. 而迭代器Iterator 是拉模式, 通过循环主动获取.

  • 事件/监听器模式

API: 类 java.util.EventObject , 接口 java.util.EventListener, 此接口是一个标识接口, 无方法.

Spring 事件/监听

ApplicationEvent: 事件. 扩展了 EventObject.
ApplicationListener: 事件监听器, 扩展了 EventListener

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 注册监听器
context.addApplicationLinstener(new ApplicationListener<MyApplicationEvent>(){

    @Override
    public void onApplicationEvent(MyApplicationEvent event){
        System.out.println("接收到事件: " + event.getSource());
    }
});
context.refresh();

// 发布事件
context.publishEvent(new MyApplicationEvent("test event"));
  • 应用场景

MyApplicationEvent 可以通过构造器等注入 context 对象, 从而能拿到工厂中的任意 bean 对象.

Spring Boot 的核心事件

  • ApplicationEnvironmentPreparedEvent
  • ApplicationPreparedEvent
  • ApplicationStartingEvent
  • ApplicationReadyEvent
  • ApplicationFailedEvent

Spring Boot 事件/监听器

  • ConfigFileApplicationListener 管理配置文件, 如 application-{profile}.properties 或 yaml 格式的文件. 通过下面入口函数找, 可以发现加载配置文件的 Loader.load() 方法
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ApplicationEnvironmentPreparedEvent) {
        onApplicationEnvironmentPreparedEvent(
                (ApplicationEnvironmentPreparedEvent) event);
    }
    if (event instanceof ApplicationPreparedEvent) {
        onApplicationPreparedEvent(event);
    }
}

/META-INF/spring.factories 文件中配置了需要加载的监听器, 其中包括了 ConfigFileApplicationListener

  • ConfigFileApplicationListener 实现了 Orderd 接口 , 用来控制顺序.

Spring Cloud 事件/监听器

  • BootstrapApplicationListener 第一, 负责加载 bootstrap.properties 或 yaml 格式的文件. 第二, 负责加载 ApplicationContext 名为 bootstrap( ConfigurableApplicationContext context = builder.run() ).

自定义配置属性

  1. 继承 PropertySourceLocator
  2. 向自定义类注解添加 @Ordered , @Configuration
  3. 添加配置到 spring.factories 文件, key为 org.springwork.cloud.bootstrap.BootstrapConfiguration

Environment 允许出现同名配置, 优先级高的胜出.

MutablePropertySources 使用了 CopyOnWriteArrayList 数据结构

public class MutablePropertySources implements PropertySources {
    // 使用了 CopyOnWriteArrayList
    private final List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<>();
    ...
}

猜你喜欢

转载自www.cnblogs.com/walkinhalo/p/10846986.html