资讯专栏INFORMATION COLUMN

Spring事件机制问题排查

alphahans / 2898人阅读

摘要:前言之前使用的事件机制来改造系统,完成了部分模块的解耦。但是实际使用时却发现存在以下问题当批量推送时,如果在处理的过程中抛出异常,则会导致后续的推送中断。但是实际上却是抛出异常会导致后续事件的推送中断。

前言

之前使用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 {

    @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.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 事件推送
 * @author RJH
 * create at 2018/10/29
 */
public class EventApplication {

    public static void main(String[] args) {
        //扫描特定package
        ApplicationContext context=new AnnotationConfigApplicationContext("com.rjh.event");
        for(int i=1;i<=100;i++){//批量推送事件
            context.publishEvent(new SimpleEvent(i));
        }
    }
}
运行结果
Time:1553607971143 event:1
Time:1553607971145 event:2
Time:1553607971145 event:3
Time:1553607971145 event:4
Time:1553607971145 event:5
Time:1553607971145 event:6
Time:1553607971146 event:7
Time:1553607971146 event:8
Time:1553607971146 event:9
Exception in thread "main" java.lang.RuntimeException
    at com.rjh.event.SimpleEventListener.onApplicationEvent(SimpleEventListener.java:17)
    at com.rjh.event.SimpleEventListener.onApplicationEvent(SimpleEventListener.java:11)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
    at com.rjh.event.EventApplication.main(EventApplication.java:17)
分析

期待结果为SimpleEventListener抛出异常不影响EventApplication中后续事件的推送。但是实际上却是SimpleEventListener抛出异常会导致EventApplication后续事件的推送中断。从这里可以看出事件的推送和事件的监听是同步阻塞进行,而并非是异步。详细可以参考文档中的介绍:

Notice that ApplicationListener is generically parameterized with the type of your custom event (BlackListEvent in the preceding example). This means that the onApplicationEvent() method can remain type-safe, avoiding any need for downcasting. You can register as many event listeners as you wish, but note that, by default, event listeners receive events synchronously. This means that the publishEvent() method blocks until all listeners have finished processing the event. One advantage of this synchronous and single-threaded approach is that, when a listener receives an event, it operates inside the transaction context of the publisher if a transaction context is available. If another strategy for event publication becomes necessary, See the javadoc for Spring’s ApplicationEventMulticaster interface.
解决办法

将事件监听改造为异步处理,这里将会展示基于JavaConfig即注解的解决方案

开启异步
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * 开启异步服务配置类
 * @author RJH
 * create at 2019-03-26
 */
@EnableAsync
@Configuration
public class AsyncConfig {

}
异步事件监听
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 异步事件监听
 * @author RJH
 * create at 2019-03-26
 */
@Component
public class AsyncSimpleEventListener {

    @EventListener
    @Async
    public void handleEvent(SimpleEvent event){
        if(event.getI()%10==0){
            throw new RuntimeException();
        }
        System.out.println("Time:"+event.getTimestamp()+" event:"+event.getSource());
    }
}
运行结果
Time:1553614469990 event:1
Time:1553614470007 event:72
Time:1553614470006 event:64
Time:1553614470006 event:67
Time:1553614470007 event:73
Time:1553614470007 event:71
Time:1553614470007 event:75
Time:1553614470006 event:68
Time:1553614470007 event:69
Time:1553614470006 event:62
Time:1553614470005 event:61
Time:1553614470006 event:63
Time:1553614470006 event:65
Time:1553614470007 event:74
Time:1553614470006 event:66
Time:1553614470005 event:59
Time:1553614470005 event:57
Time:1553614470005 event:55
Time:1553614470005 event:58
Time:1553614470004 event:51
Time:1553614470004 event:52
Time:1553614470002 event:43
Time:1553614470004 event:53
Time:1553614470002 event:38
Time:1553614470001 event:36
Time:1553614470004 event:54
Time:1553614470001 event:33
Time:1553614470000 event:29
Time:1553614470000 event:27
Time:1553614470005 event:56
Time:1553614469999 event:23
Time:1553614469999 event:22
Time:1553614469999 event:21
三月 26, 2019 11:34:30 下午 org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler handleUncaughtException
严重: Unexpected error occurred invoking async method: public void com.rjh.event.AsyncSimpleEventListener.handleEvent(com.rjh.event.SimpleEvent)
Time:1553614470000 event:24java.lang.RuntimeException
    at com.rjh.event.AsyncSimpleEventListener.handleEvent(AsyncSimpleEventListener.java:19)

    at com.rjh.event.AsyncSimpleEventListener$$FastClassBySpringCGLIB$$61742dbf.invoke()
Time:1553614469998 event:15    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:736)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)

    at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:115)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
...内容过长省略部分结果
分析

改造为异步执行后,事件监听就由线程池进行处理,此处还可以通过自定义线程池,并设置异常处理器来处理未捕获的异常。

参考资料

https://docs.spring.io/spring...

https://docs.spring.io/spring...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73959.html

相关文章

  • Java面试 32个核心必考点完全解析

    摘要:如问到是否使用某框架,实际是是问该框架的使用场景,有什么特点,和同类可框架对比一系列的问题。这两个方向的区分点在于工作方向的侧重点不同。 [TOC] 这是一份来自哔哩哔哩的Java面试Java面试 32个核心必考点完全解析(完) 课程预习 1.1 课程内容分为三个模块 基础模块: 技术岗位与面试 计算机基础 JVM原理 多线程 设计模式 数据结构与算法 应用模块: 常用工具集 ...

    JiaXinYi 评论0 收藏0
  • 互联网后端知识点整理

    摘要:前言一些问题的整理,平时实际工作中可能会忽视的一些原理性问题,后续会选取一些有意思的点进行详述。 前言 一些问题的整理,平时实际工作中可能会忽视的一些原理性问题,后续会选取一些有意思的点进行详述。 JAVA多线程、并发相关 多个线程同时读写,读线程的数量远远⼤于写线程,你认为应该如何解决 并发的问题?你会选择加什么样的锁? JAVA的AQS是否了解,它是⼲嘛的? 除了synchron...

    kaka 评论0 收藏0
  • Javag工程师成神之路(2019正式版)

    摘要:结构型模式适配器模式桥接模式装饰模式组合模式外观模式享元模式代理模式。行为型模式模版方法模式命令模式迭代器模式观察者模式中介者模式备忘录模式解释器模式模式状态模式策略模式职责链模式责任链模式访问者模式。 主要版本 更新时间 备注 v1.0 2015-08-01 首次发布 v1.1 2018-03-12 增加新技术知识、完善知识体系 v2.0 2019-02-19 结构...

    Olivia 评论0 收藏0
  • Java面试通关要点汇总集

    摘要:本文会以引出问题为主,后面有时间的话,笔者陆续会抽些重要的知识点进行详细的剖析与解答。敬请关注服务端思维微信公众号,获取最新文章。 原文地址:梁桂钊的博客博客地址:http://blog.720ui.com 这里,笔者结合自己过往的面试经验,整理了一些核心的知识清单,帮助读者更好地回顾与复习 Java 服务端核心技术。本文会以引出问题为主,后面有时间的话,笔者陆续会抽些重要的知识点进...

    gougoujiang 评论0 收藏0
  • 2021 年最新基于 Spring Cloud 的微服务架构分析

    摘要:是一个相对比较新的微服务框架,年才推出的版本虽然时间最短但是相比等框架提供的全套的分布式系统解决方案。提供线程池不同的服务走不同的线程池,实现了不同服务调用的隔离,避免了服务器雪崩的问题。通过互相注册的方式来进行消息同步和保证高可用。 Spring Cloud 是一个相对比较新的微服务框架,...

    cikenerd 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<