Spring中的事件驱动模型(一)

事件驱动模型简介

事件驱动模型一般也被理解成观察者或者发布/订阅模型。java

  • 是一种对象间的一对多的关系;
  • 当目标发送改变(发布),观察者(订阅者)就能够接收到改变;
  • 观察者如何处理,目标无需干涉,它们之间的关系是松耦合的。

event-source
事件驱动模型

事件驱动模型的例子不少,如生活中的红绿灯,以及咱们在微服务中用到的配置中心,当有配置提交时出发具体的应用实例更新Spring上下文环境。web

Spring的事件机制

基本概念

Spring的事件驱动模型由三部分组成:微信

  • 事件:ApplicationEvent,继承自JDK的EventObject,全部事件将继承它,并经过source获得事件源。
  • 事件发布者:ApplicationEventPublisher及ApplicationEventMulticaster接口,使用这个接口,咱们的Service就拥有了发布事件的能力。
  • 事件订阅者:ApplicationListener,继承自JDK的EventListener,全部监听器将继承它。

Spring事件驱动过程

事件

Spring 默认对 ApplicationEvent 事件提供了以下实现:框架

  • ContextStoppedEvent:ApplicationContext中止后触发的事件;
  • ContextRefreshedEvent:ApplicationContext初始化或刷新完成后触发的事件;
  • ContextClosedEvent:ApplicationContext关闭后触发的事件。如web容器关闭时自动会触发Spring容器的关闭,若是是普通java应用,须要调用ctx.registerShutdownHook()注册虚拟机关闭时的钩子才行;
  • ContextStartedEvent:ApplicationContext启动后触发的事件;

eventobject
事件

public abstract class ApplicationEvent extends EventObject {
    private static final long serialVersionUID = 7099057708183571937L;
    //事件发生的时间
    private final long timestamp = System.currentTimeMillis();
	//建立一个新的ApplicationEvent事件
    public ApplicationEvent(Object source) {
        super(source);
    }

    public final long getTimestamp() {
        return this.timestamp;
    }
}
复制代码

事件基类ApplicationEvent,全部的具体事件都会继承该抽象事件类。异步

事件监听者

ApplicationListener
事件监听
ApplicationListener继承自JDK的 EventListener,JDK要求全部监听器将继承它。

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    void onApplicationEvent(E var1);
}
复制代码

提供了onApplicationEvent方法,用以处理ApplicationEvent,不过对于具体事件的处理须要进行判断。而GenericApplicationListenerSmartApplicationListener提供了关于事件更多的元数据信息。ide

public class SourceFilteringListener implements GenericApplicationListener, SmartApplicationListener {

	private final Object source;

	@Nullable
	private GenericApplicationListener delegate;

	//为特定事件源建立SourceFilteringListener,并传入代理的监听器类
	public SourceFilteringListener(Object source, ApplicationListener<?> delegate) {
		this.source = source;
		this.delegate = (delegate instanceof GenericApplicationListener ?
				(GenericApplicationListener) delegate : new GenericApplicationListenerAdapter(delegate));
	}
	//....省略部分代码
	
	@Override
	public int getOrder() {
		return (this.delegate != null ? this.delegate.getOrder() : Ordered.LOWEST_PRECEDENCE);
	}

	//过滤以后实际处理事件
	protected void onApplicationEventInternal(ApplicationEvent event) {
		//...
		this.delegate.onApplicationEvent(event);
	}

}
复制代码

SourceFilteringListenerApplicationListener的装饰器类,过滤特定的事件源。只会注入其事件对应的代理监听器,还提供了按照顺序触发监听器等功能。 在启动的时候会加载一部分 ApplicationListener。Spring Context加载初始化完成(refresh)后会再次检测应用中的 ApplicationListener,而且注册,此时会将咱们实现的 ApplicationListener 就会加入到 SimpleApplicationEventMulticaster 维护的 Listener 集合中。 Spring也支持直接注解的形式进行事件监听@EventListener(Event.class)微服务

事件发布

EventPublisher
发布事件
ApplicationContext接口继承了 ApplicationEventPublisher,并在 AbstractApplicationContext实现了具体代码,实际执行是委托给 ApplicationEventMulticaster

@FunctionalInterface
public interface ApplicationEventPublisher {
	//通知全部的注册该事件的应用,事件能够是框架事件如RequestHandledEvent或者特定的应用事件。
    default void publishEvent(ApplicationEvent event) {
        this.publishEvent((Object)event);
    }

    void publishEvent(Object var1);
}
复制代码

实际的执行是委托给,读者有兴趣能够看一下AbstractApplicationContext中这部分的逻辑。下面咱们具体看一下ApplicationEventMulticaster接口中定义的方法。源码分析

public interface ApplicationEventMulticaster {

	//增长监听者
	void addApplicationListener(ApplicationListener<?> listener);
	//...

	//移除监听者
	void removeApplicationListener(ApplicationListener<?> listener);
	//...
	
	//广播特定事件给监听者
	void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType);

}
复制代码

AbstractApplicationContext中定义了对监听者的操做维护,如增长和删除,并提供了将特定事件进行广播的方法。下面看一下具体实现类SimpleApplicationEventMulticasterApplicationContext自动到本地容器里找一个ApplicationEventMulticaster实现,若是没有则会使用默认的SimpleApplicationEventMulticasterthis

public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {

	@Nullable
	private Executor taskExecutor;

	//...
	
	//用给定的beanFactory建立SimpleApplicationEventMulticaster
	public SimpleApplicationEventMulticaster(BeanFactory beanFactory) {
		setBeanFactory(beanFactory);
	}

	@Override
	public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
		ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
		for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
			Executor executor = getTaskExecutor();
			if (executor != null) {
				executor.execute(() -> invokeListener(listener, event));
			}
			else {
				invokeListener(listener, event);
			}
		}
	}

	//注入给定事件的给定监听器
	protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
		ErrorHandler errorHandler = getErrorHandler();
		if (errorHandler != null) {
			try {
				doInvokeListener(listener, event);
			}
			...
		}
		else {
			doInvokeListener(listener, event);
		}
	}

	@SuppressWarnings({"unchecked", "rawtypes"})
	private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
		try {
			listener.onApplicationEvent(event);
		}
		//...
	}

}
复制代码

multicastEvent方法中,executor不为空的状况下,能够看到是支持异步发布事件。发布事件时只须要调用ApplicationContext中的publishEvent方法便可进行事件的发布。spa

总结

本文主要介绍了Spring中的事件驱动模型相关概念。首先介绍事件驱动模型,也能够说是观察者模式,在咱们的平常生活中和应用开发中有不少应用。随后重点篇幅介绍了Spring的事件机制,Spring的事件驱动模型由事件、发布者和订阅者三部分组成,结合Spring的源码分析了这三部分的定义与实现。笔者将会在下一篇文章,结合具体例子以及Spring Cloud Config中的实现进行实战讲解。

订阅最新文章,欢迎关注个人公众号

微信公众号

参考

  1. 事件驱动模型简介
  2. Spring事件驱动模型与观察者模式
相关文章
相关标签/搜索