同步事件和异步事件

  • 同步事件: 在一个线程里,按顺序执行业务,做完一件事再去做下一件事。
  • 异步事件: 在一个线程里,做一个事的同事,可以另起一个新的线程执行另一件事,这样两件事可以同时执行。

  用一个例子来解释同步事件和异步事件的使用场景,有时候一段完整的代码逻辑,可能分为几部分,拿最常见的注册来说,假设完整流程是,1.点击注册->2.检验信息并存库->3.发送邮件通知->4.返回给用户.代码这么写是正确,但不是最好的,缺点如下:

  1. 逻辑复杂,业务耦合,我们把校验数据并存库和发送邮件写到一个大的业务方法里了,发送邮件我们可以看做一个相对独立的业务方法。
  2. 效率低,假设2和3分别需要1秒的时候,那么用户在点击注册2秒后才能看到响应。

  同步事件可以解决上面第一个问题,我们把发邮件的方法独立出来,放到事件里执行,这样注册的这个方法就可以只做2操作,完成之后发布一个事件去执行3,可以很好的解决业务耦合的问题.

  异步事件可以完美解决以上两个问题,注册方法执行2操作,执行之后发布一个异步事件,另起一个线程执行3操作,注册方法所在的线程可直接返回给用户,这样不仅实现了业务解耦还提高了效率,用户点击注册,1秒后就能看到响应.

Spring的事件机制

  Spring 事件发送监听涉及3个部分

  ApplicationEvent:表示事件本身,自定义事件需要继承该类,可以用来传递数据,比如上述操作,我们需要将用户的邮箱地址传给事件监听器.

  • ApplicationEventPublisherAware :事件发送器,通过实现这个接口,来触发事件.  
  • ApplicationListener:事件监听器接口,事件的业务逻辑封装在监听器里面.

接下来使用spring的异步事件机制来模拟上面的注册流程.有配置文件和注解两种方式。

使用配置文件的方式创建事件:

新建TestEvent:

 public class TestEvent extends ApplicationEvent {
 
     private TestParam source;
 
     public TestEvent(TestParam source) {
         super(source);
         this.source = source;
     }
 }
 
 @Data
 public class TestParam {
     private String email;
 }

新建TestListener:

 @Component
 public class TestListener implements ApplicationListener<TestEvent> {
 
     @Override
     public void onApplicationEvent(TestEvent testEvent) {
 
         TestParam param = (TestParam) testEvent.getSource();
         System.out.println(".......开始.......");
         System.out.println("发送邮件:"+param.getEmail());
         System.out.println(".......结束.....");
     }
 }

新建 EventPublisher:

@Component
public class TestPublish implements ApplicationEventPublisherAware {

    private static ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        TestPublish.applicationEventPublisher = applicationEventPublisher;
    }

    public static void  publishEvent(ApplicationEvent communityArticleEvent) {
        applicationEventPublisher.publishEvent(communityArticleEvent);
    }
}

spring-context.xml中添加:

  <bean id="applicationEventAsyncMulticaster" class="org.springframework.context.event.SimpleApplicationEventMulticaster">
         <property name="taskExecutor">
             <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
                 <property name="corePoolSize" value="5"/>
                 <property name="keepAliveSeconds" value="3000"/>
                 <property name="maxPoolSize" value="50"/>
                 <property name="queueCapacity" value="200"/>
             </bean>
         </property>
     </bean>

注意:如果加<propery name="taskExecutor",则使用异步方式执行,否则为同步方式

使用注解方式创建事件

使用 @Async 需要在配置文件添加一下支持,线程池也是需要配置一下的

<!-- 开启@AspectJ AOP代理 -->
    <aop:aspectj-autoproxy proxy-target-class="true"/>

    <!-- 任务执行器 -->
    <task:executor id="executor" pool-size="10"/>

    <!--开启注解调度支持 @Async -->
    <task:annotation-driven executor="executor" proxy-target-class="true"/>

  TestListener中在方法中添加@Async

 @Component
 public class TestListener implements ApplicationListener<TestEvent> {
 
     @Async
     @Override
     public void onApplicationEvent(TestEvent testEvent) {
 
         TestParam param = (TestParam) testEvent.getSource();
         System.out.println(".......开始.......");
         System.out.println("发送邮件:"+param.getEmail());
         System.out.println(".......结束.....");
     }
 }

 Listener其实还可以做得更彻底一点,使用注解@EventListener可代替实现ApplicationListener,原理是通过扫描这个注解来创建监听器并自动添加到ApplicationContext中.

新建自定义EventHandler:

 @Component
 public class TestEventHandler {
 
     @Async
     @EventListener
     public void handleTestEvent(TestEvent testEvent) {
 
         TestParam param = (TestParam) testEvent.getSource();
         System.out.println(".......开始.......");
         System.out.println("发送邮件:"+param.getEmail());
         System.out.println(".......结束.....");
     }
 } 

测试及控制台的打印就不贴了,这里主要记录一下具体的实现方法.

总结:

  使用spring事件机制能很好地帮助我们消除不同业务间的耦合关系,也可以提高执行效率,应该根据业务场景灵活选择。