一.事件机制基本概念
java中的事件机制的参与者有3种角色:
- 1.event object(ApplicationEvent):事件状态对象,用于listener的相应的方法之中,作为参数,一般存在与listerner的方法之中
- 2.event listener(ApplicationListener):对每个明确的事件的发生,都相应地定义一个明确的Java方法。这些方法都集中定义在事件监听者(EventListener)接口中,
这个接口要继承 java.util.EventListener。 实现了事件监听者接口中一些或全部方法的类就是事件监听者。 - 3.event source(ApplicationContext):具体的事件源,比如说,你点击一个button(或者调用ApplicationContext.publishEvent()方法),那么button就是event source,要想使button对某些事件进行响应,你就需要注册特定的listener。
二.Spring事件驱动体系使用
spring事件驱动依赖jdk实现.本文只分析主流程.
以改造如下代码实现异步解耦讲解

@Service
public class OrderServiceImpl2 implements OrderService {
@Override
public void saveOder() {
//1、创建订单
System.out.println("订单创建成功");
//2、发送短信通知
System.out.println("用户您好,恭喜您抢购成功~来自短信");
//3、发送微信通知
System.out.println("用户您好,恭喜您抢购成功~来自微信");
//4、发送小程序通知
System.out.println("用户您好,恭喜您抢购成功~来自小程序");
}
}
-
a)首先声明一个事件:OrderCreateEvent
//继承ApplicationEvent即可 public class OrderCreateEvent extends ApplicationEvent { //默认覆盖 public OrderCreateEvent(Object source) { super(source); } } -
b) 所有通知 实现ApplicationListener
-
进行短信通知
@Component //交给spring管理 实现接口并监听事件源 public class MessageListener implements ApplicationListener<OrderCreateEvent> { @Async //可以异步执行 @Override //覆盖方法 即可实现具体的业务操作 public void onApplicationEvent(OrderCreateEvent orderCreateEvent) { System.out.println(orderCreateEvent.getSource()+",message is sending"); } } -
进行微信通知
@Component public class WeixinListener implements ApplicationListener<OrderCreateEvent> { @Async @Override public void onApplicationEvent(OrderCreateEvent orderCreateEvent) { System.out.println(orderCreateEvent.getSource()+",weixin is sending"); } } -
小程序通知
@Component public class LittleProListener implements ApplicationListener<OrderCreateEvent> { @Async @Override public void onApplicationEvent(OrderCreateEvent orderCreateEvent) { System.out.println(orderCreateEvent.getSource()+",xiao cheng xu is sending ..."); } }
-
c) 创建订单并发布事件
@Service public class OrderServiceImpl implements OrderService { @Autowired ApplicationContext applicationContext; @Override public void saveOder() { //1、创建订单 System.out.println("订单创建成功"); //创建订单创建的事件 OrderCreateEvent orderCreateEvent = new OrderCreateEvent("order create is success"); //利用applicationContext将事件发布 applicationContext.publishEvent(orderCreateEvent); //2、发送短信通知 //3、发送微信通知 //4、发送小程序通知 } }
三.Spring事件驱动体系实现
a) 事件的具体代表者是:ApplicationEvent,其继承自JDK的EventObject,JDK要求所有事件将继承它,并通过source得到事件源;

a)ContextStartedEvent:ApplicationContext启动后触发的事件;(目前版本没有任何作用)
b)ContextStoppedEvent:ApplicationContext停止后触发的事件;(目前版本没有任何作用)
c)ContextRefreshedEvent:ApplicationContext初始化或刷新完成后触发的事件;(容器初始化完成后调用)
d)ContextClosedEvent:ApplicationContext关闭后触发的事件;(如web容器关闭时自动会触发spring容器的关闭,如果是普通java应用,需要调用ctx.registerShutdownHook();注册虚拟机关闭时的钩子才行)
注:org.springframework.context.support.AbstractApplicationContext抽象类实现了LifeCycle的start和stop回调并发布ContextStartedEvent和ContextStoppedEvent事件;但是无任何实现调用它,所以目前无任何作用。
b) 监听者,具体实现者:ApplicationListener, 其继承自JDK的EventListener,JDK要求所有监听器将继承它;
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
/**
* Handle an application event.
* @param event the event to respond to
*/
void onApplicationEvent(E event);
}
c)事件发布者,具体代表者:ApplicationEventPublisher及ApplicationEventMulticaster(多播),
系统默认提供了如下实现:


1.AbstractApplicationContext的发布方法,传入事件源
public void publishEvent(ApplicationEvent event) {
//省略部分代码
getApplicationEventMulticaster().multicastEvent(event);//调用SimpleApplicationEventMulticaster.multicastEvent
if (this.parent != null) {
this.parent.publishEvent(event);
}
}
-
SimpleApplicationEventMulticaster.multicastEvent方法遍历所有的listener调用invokeListener
public void multicastEvent(final ApplicationEvent event) { for (final ApplicationListener<?> listener : getApplicationListeners(event)) { Executor executor = getTaskExecutor(); if (executor != null) { executor.execute(new Runnable() { @Override public void run() { invokeListener(listener, event); } }); } else { invokeListener(listener, event); } } } -
返回所有匹配的通知
protected Collection<ApplicationListener<?>> getApplicationListeners(ApplicationEvent event) { Object source = event.getSource(); Class<?> sourceType = (source != null ? source.getClass() : null); ListenerCacheKey cacheKey = new ListenerCacheKey(event.getClass(), sourceType); // Quick check for existing entry on ConcurrentHashMap... ListenerRetriever retriever = this.retrieverCache.get(cacheKey); if (retriever != null) { return retriever.getApplicationListeners(); } if (this.beanClassLoader == null || (ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) && (sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader)))) { // Fully synchronized building and caching of a ListenerRetriever synchronized (this.retrievalMutex) { retriever = this.retrieverCache.get(cacheKey); if (retriever != null) { return retriever.getApplicationListeners(); } retriever = new ListenerRetriever(true); Collection<ApplicationListener<?>> listeners = retrieveApplicationListeners(event, sourceType, retriever); this.retrieverCache.put(cacheKey, retriever); return listeners; } } else { // No ListenerRetriever caching -> no synchronization necessary return retrieveApplicationListeners(event, sourceType, null); } } -
invokeListener方法即开始调用所有通知类重写的onApplicationEvent方法实现事件通知
protected void invokeListener(ApplicationListener listener, ApplicationEvent event) { ErrorHandler errorHandler = getErrorHandler(); if (errorHandler != null) { try { listener.onApplicationEvent(event); } catch (Throwable err) { errorHandler.handleError(err); } } else { listener.onApplicationEvent(event); } }
1300




被折叠的 条评论
为什么被折叠?



