前言
之前使用Spring
的事件机制来改造系统,完成了部分模块的解耦。但是实际使用时却发现存在以下问题:
当ApplicationEventPublisher
批量推送ApplicationEvent
时,如果ApplicationListener
在处理的过程中抛出异常,则会导致后续的推送中断。
PS:Spring
版本为5.1.5.RELEASE
下面将会展示一个复盘的示例
复盘示例
自定义事件
import org.springframework.context.ApplicationEvent;
/**
* 自定义事件
* @author RJH
* create at 2018/10/29
*/
public class SimpleEvent extends ApplicationEvent {
private int i;
/**
* Create a new ApplicationEvent.
*
* @param source the object on which the event initially occurred (never {@code null})
*/
public SimpleEvent(Object source) {
super(source);
i=Integer.valueOf(source.toString());
}
public int getI() {
return i;
}
}
事件监听器
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* 自定义事件监听器
* @author RJH
* create at 2018/10/29
*/
@Component
public class SimpleEventListener implements ApplicationListener<SimpleEvent> {
@Override
public void onApplicationEvent(SimpleEvent event) {
if(event.getI()%10==0){
throw new RuntimeException();
}
System.out.println("Time:"+event.getTimestamp()+" event:"+event.getSource());
}
}
事件推送
import org.springframewor