Spring源码之事件驱动模型

xiaoxiao2021-02-28  3

SpringContext中初始化事件发布者 ###

//spring初始化事件的地方 //spring初始化事件的地方 public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext, DisposableBean { /** 用于事件发布 */ private ApplicationEventMulticaster applicationEventMulticaster; /** 静态指定的监听器*/ private Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<ApplicationListener<?>>(); //======省略一段代码========/ public void refresh() throws BeansException, IllegalStateException { //======省略一段代码========/ // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // 检查监听器bean并注册它们。 registerListeners(); //======省略一段代码========/ } //======省略一段代码========/ /** * 初始化ApplicationEventMulticaster. * <p>如果在上下文中没有定义,则使用SimpleApplicationEventMulticaster。 * @see org.springframework.context.event.SimpleApplicationEventMulticaster */ protected void initApplicationEventMulticaster() { //获取bean工厂 ConfigurableListableBeanFactory beanFactory = getBeanFactory(); //先找工厂中ApplicationEventMulticaster是否有对应的实例(注册过) if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isDebugEnabled()) { logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else {//没有对应的实例,则自己初始化一个,可以看到没有初始化线程次,所以默认是同步调用 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isDebugEnabled()) { logger.debug("Unable to locate ApplicationEventMulticaster with name '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "': using default [" + this.applicationEventMulticaster + "]"); } } } /** * 添加实现ApplicationListener的bean作为监听器 * Doesn't affect other listeners, which can be added without being beans. */ protected void registerListeners() { // 首先注册静态指定的监听器。 for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } /** *不要在这里初始化FactoryBeans:我们需要将所有常规的bean保留为初始化,以便后bean后置处理器适用于它们! */ //查找所有ApplicationListener类型的类 //includeNonSingletons为false表示只取单例Bean,true则不是 //allowEagerInit为true表示立刻加载,false表示延迟加载。 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String lisName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(lisName); } } //发布事件 public void publishEvent(ApplicationEvent event) { Assert.notNull(event, "Event must not be null"); if (logger.isTraceEnabled()) { logger.trace("Publishing event in " + getDisplayName() + ": " + event); } //获取applicationEventMulticaster对象,调用multicastEvent(event)方法 getApplicationEventMulticaster().multicastEvent(event); if (this.parent != null) { this.parent.publishEvent(event); } } } //可以看到,如果要实现异步的事件发布,id必须为“applicationEventMulticaster” <bean id="applicationEventMulticaster" class="org.springframework.context.event.SimpleApplicationEventMulticaster"> <!-- 注入任务执行器 这样就实现了异步调用(缺点是全局的,要么全部异步,要么全部同步(删除这个属性即是同步)) --> <property name="taskExecutor" ref="executor"/> </bean>

事件ApplicationEvent

//第一部分:spring事件消息对象 public class EventObject implements java.io.Serializable { private static final long serialVersionUID = 5516075349620653480L; /** * 事件最初发生的对象。 */ protected transient Object source; //构造方法 public EventObject(Object source) { if (source == null) throw new IllegalArgumentException("null source"); this.source = source; } public Object getSource() { return source; } public String toString() { return getClass().getName() + "[source=" + source + "]"; } } //抽象类 public abstract class ApplicationEvent extends EventObject { /** use serialVersionUID from Spring 1.2 for interoperability */ private static final long serialVersionUID = 7099057708183571937L; /** System time when the event happened */ private final long timestamp; /** * Create a new ApplicationEvent. * @param source the component that published the event (never {@code null}) */ public ApplicationEvent(Object source) { super(source); this.timestamp = System.currentTimeMillis(); } /** * Return the system time in milliseconds when the event happened. */ public final long getTimestamp() { return this.timestamp; } }

目标(发布事件者)ApplicationEventMulticaster (核心)

//第二部分:应用程序事件广播接口 public interface ApplicationEventMulticaster { /** * 添加一个监听器bean * @param listener the listener to add */ void addApplicationListener(ApplicationListener listener); /** * 添加一个监听器的beanName * @param listenerBeanName the name of the listener bean to add */ void addApplicationListenerBean(String listenerBeanName); /** * 删除一个监听器bean * @param listener the listener to remove */ void removeApplicationListener(ApplicationListener listener); /** * 添加一个监听器beanName * @param listenerBeanName the name of the listener bean to add */ void removeApplicationListenerBean(String listenerBeanName); /** * 删除所有在这个Multicaster注册的监听者。 */ void removeAllListeners(); /** * 将给定的应用程序事件组播到适当的侦听器。 * @param event the event to multicast */ void multicastEvent(ApplicationEvent event); } //标记接口 public interface Aware { } //标记可以设置BeanFactory public interface BeanFactoryAware extends Aware { void setBeanFactory(BeanFactory beanFactory) throws BeansException; } //标记可以设置bean的类加载器 public interface BeanClassLoaderAware extends Aware { void setBeanClassLoader(ClassLoader classLoader); } //完成了默认实现,应用程序事件广播抽象类 public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware { //监听者(内部持有:监听实例 和 监听者beanName) private final ListenerRetriever defaultRetriever = new ListenerRetriever(false); private final Map<ListenerCacheKey, ListenerRetriever> retrieverCache = new ConcurrentHashMap<ListenerCacheKey, ListenerRetriever>(64); //类加器: 不为null时,则检查 eventType和sourceType是否由给定的ClassLoader或其父级加载。 private ClassLoader beanClassLoader; //bean工厂:用于获取defaultRetriever中listenerBeanName所对应的bean实例 private BeanFactory beanFactory; //添加一个监听器bean public void addApplicationListener(ApplicationListener listener) { synchronized (this.defaultRetriever) { this.defaultRetriever.applicationListeners.add(listener); this.retrieverCache.clear(); } } //添加一个监听器beanName public void addApplicationListenerBean(String listenerBeanName) { synchronized (this.defaultRetriever) { this.defaultRetriever.applicationListenerBeans.add(listenerBeanName); this.retrieverCache.clear(); } } //删除一个监听器bean public void removeApplicationListener(ApplicationListener listener) { synchronized (this.defaultRetriever) { this.defaultRetriever.applicationListeners.remove(listener); this.retrieverCache.clear(); } } //删除一个监听器beanName public void removeApplicationListenerBean(String listenerBeanName) { synchronized (this.defaultRetriever) { this.defaultRetriever.applicationListenerBeans.remove(listenerBeanName); this.retrieverCache.clear(); } } //删除所有监听器 public void removeAllListeners() { synchronized (this.defaultRetriever) { this.defaultRetriever.applicationListeners.clear(); this.defaultRetriever.applicationListenerBeans.clear(); this.retrieverCache.clear(); } } public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; if (this.beanClassLoader == null && beanFactory instanceof ConfigurableBeanFactory) { this.beanClassLoader = ((ConfigurableBeanFactory) beanFactory).getBeanClassLoader(); } } private BeanFactory getBeanFactory() { if (this.beanFactory == null) { throw new IllegalStateException("ApplicationEventMulticaster cannot retrieve listener beans " + "because it is not associated with a BeanFactory"); } return this.beanFactory; } //返回所有监听者实例列表 protected Collection<ApplicationListener> getApplicationListeners() { synchronized (this.defaultRetriever) { return this.defaultRetriever.getApplicationListeners(); } } //返回与给定事件类型匹配的ApplicationListeners集合。 不匹配的听众早日被排除在外。 protected Collection<ApplicationListener> getApplicationListeners(ApplicationEvent event) { Class<? extends ApplicationEvent> eventType = event.getClass(); Object source = event.getSource(); Class<?> sourceType = (source != null ? source.getClass() : null); ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType); // 先走缓存 ListenerRetriever retriever = this.retrieverCache.get(cacheKey); if (retriever != null) { return retriever.getApplicationListeners(); } //缓存中没有 if (this.beanClassLoader == null || //在给定的上下文中,检查给定的类是否是缓存安全的,即是否由给定的ClassLoader或其父级加载。 (ClassUtils.isCacheSafe(eventType, this.beanClassLoader) && (sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader)))) { // Fully synchronized building and caching of a ListenerRetriever synchronized (this.defaultRetriever) { retriever = this.retrieverCache.get(cacheKey); if (retriever != null) { return retriever.getApplicationListeners(); } retriever = new ListenerRetriever(true); Collection<ApplicationListener> listeners = retrieveApplicationListeners(eventType, sourceType, retriever); //放入缓存 this.retrieverCache.put(cacheKey, retriever); return listeners; } } else { //没有ListenerRetriever缓存 - >不需要synchronization return retrieveApplicationListeners(eventType, sourceType, null); } } /** * 实际检索给定事件和源类型的应用程序监听器列表。 * @param eventType the application event type * @param sourceType the event source type * @param retriever the ListenerRetriever, if supposed to populate one (for caching purposes) * @return the pre-filtered list of application listeners for the given event and source type */ private Collection<ApplicationListener> retrieveApplicationListeners( Class<? extends ApplicationEvent> eventType, Class<?> sourceType, ListenerRetriever retriever) { LinkedList<ApplicationListener> allListeners = new LinkedList<ApplicationListener>(); Set<ApplicationListener> listeners; Set<String> listenerBeans; synchronized (this.defaultRetriever) { listeners = new LinkedHashSet<ApplicationListener>(this.defaultRetriever.applicationListeners); listenerBeans = new LinkedHashSet<String>(this.defaultRetriever.applicationListenerBeans); } for (ApplicationListener listener : listeners) { if (supportsEvent(listener, eventType, sourceType)) { if (retriever != null) { retriever.applicationListeners.add(listener); } allListeners.add(listener); } } if (!listenerBeans.isEmpty()) { BeanFactory beanFactory = getBeanFactory(); for (String listenerBeanName : listenerBeans) { ApplicationListener listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class); if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) { if (retriever != null) { retriever.applicationListenerBeans.add(listenerBeanName); } allListeners.add(listener); } } } OrderComparator.sort(allListeners); return allListeners; } //确定给定的侦听器是否支持给定的事件。 protected boolean supportsEvent( ApplicationListener listener, Class<? extends ApplicationEvent> eventType, Class<?> sourceType) { SmartApplicationListener smartListener = (listener instanceof SmartApplicationListener ? (SmartApplicationListener) listener : new GenericApplicationListenerAdapter(listener)); return (smartListener.supportsEventType(eventType) && smartListener.supportsSourceType(sourceType)); } /** * Cache key for ListenerRetrievers, based on event type and source type. * 基于事件类型和源类型的ListenerRetrievers缓存键。 */ private static class ListenerCacheKey { //事件类型 private final Class<?> eventType; //source类型 private final Class<?> sourceType; public ListenerCacheKey(Class<?> eventType, Class<?> sourceType) { this.eventType = eventType; this.sourceType = sourceType; } @Override public boolean equals(Object other) { if (this == other) { return true; } ListenerCacheKey otherKey = (ListenerCacheKey) other; return ObjectUtils.nullSafeEquals(this.eventType, otherKey.eventType) && ObjectUtils.nullSafeEquals(this.sourceType, otherKey.sourceType); } @Override public int hashCode() { return ObjectUtils.nullSafeHashCode(this.eventType) * 29 + ObjectUtils.nullSafeHashCode(this.sourceType); } } //Helper类封装了一组特定的目标监听器,可以有效地检索预过滤的监听器。 //<p>每个事件类型和源类型都会缓存此帮助器的一个实例。 private class ListenerRetriever { //监听者bean实例列表 public final Set<ApplicationListener> applicationListeners; //监听者bean名称列表 public final Set<String> applicationListenerBeans; //预过滤 private final boolean preFiltered; public ListenerRetriever(boolean preFiltered) { this.applicationListeners = new LinkedHashSet<ApplicationListener>(); this.applicationListenerBeans = new LinkedHashSet<String>(); this.preFiltered = preFiltered; } //返回监听者实例列表 public Collection<ApplicationListener> getApplicationListeners() { LinkedList<ApplicationListener> allListeners = new LinkedList<ApplicationListener>(); for (ApplicationListener listener : this.applicationListeners) { allListeners.add(listener); } if (!this.applicationListenerBeans.isEmpty()) { //获取给定的bean工厂 BeanFactory beanFactory = getBeanFactory(); for (String listenerBeanName : this.applicationListenerBeans) { //给定类加载加载监听者bean实例(标记一) ApplicationListener listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class); //需要预过滤 则先判断 (标记一加载实例)是否在allListeners中;不在,则添加 if (this.preFiltered || !allListeners.contains(listener)) { allListeners.add(listener); } } } //排序 OrderComparator.sort(allListeners); return allListeners; } } } //spring默认实现的 public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster { //线程池 private Executor taskExecutor; //构造方法 public SimpleApplicationEventMulticaster() { } /** * Create a new SimpleApplicationEventMulticaster for the given BeanFactory. */ public SimpleApplicationEventMulticaster(BeanFactory beanFactory) { setBeanFactory(beanFactory); } //设置Executor实例用来执行执行应用程序侦听器。 public void setTaskExecutor(Executor taskExecutor) { this.taskExecutor = taskExecutor; } protected Executor getTaskExecutor() { return this.taskExecutor; } @SuppressWarnings("unchecked") public void multicastEvent(final ApplicationEvent event) { for (final ApplicationListener listener : getApplicationListeners(event)) { Executor executor = getTaskExecutor(); //利用线程次调用监听者方法(异步,需用户指定Executor实例) if (executor != null) { executor.execute(new Runnable() { public void run() { listener.onApplicationEvent(event); } }); } else {//遍历监听器(默认:同步执行) listener.onApplicationEvent(event); } } } }

监听器 EventListener

public interface EventListener { } public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { /** * 处理事件消息的地方 * @param event the event to respond to */ void onApplicationEvent(E event); }
转载请注明原文地址: https://www.6miu.com/read-250211.html

最新回复(0)