Spring的事件机制详解

同步事件和异步事件

  同步事件:在一个线程里,按顺序执行业务,做完一件事再去做下一件事.

      异步事件:在一个线程里,做一个事的同事,可以另起一个新的线程执行另一件事,这样两件事可以同时执行.

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

          1.逻辑复杂,业务耦合,我们把校验数据并存库和发送邮件写到一个大的业务方法里了,发邮件我们可以看做一个相对独立的业务方法

    2.效率低,假设2和3分别需要1秒的时候,那么用户在点击注册2秒后才能看到相应

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

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

Spring的事件机制

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

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

  ApplicationEventPublisherAware:事件发送器,通过实现这个接口,来触发事件.

  ApplicationListener:事件监听器接口,事件的业务逻辑封装在监听器里面.

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

配置文件的方式:

  新建TestEvent:

 1 public class TestEvent extends ApplicationEvent {
 2 
 3     private TestParam source;
 4 
 5     public TestEvent(TestParam source) {
 6         super(source);
 7         this.source = source;
 8     }
 9 }
10 
11 @Data
12 public class TestParam {
13     private String email;
14 }

新建TestListener:

 1 @Component
 2 public class TestListener implements ApplicationListener<TestEvent> {
 3 
 4     @Override
 5     public void onApplicationEvent(TestEvent testEvent) {
 6 
 7         TestParam param = (TestParam) testEvent.getSource();
 8         System.out.println(".......开始.......");
 9         System.out.println("发送邮件:"+param.getEmail());
10         System.out.println(".......结束.....");
11     }
12 }

新建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中添加:

 1  <bean id="applicationEventAsyncMulticaster" class="org.springframework.context.event.SimpleApplicationEventMulticaster">
 2         <property name="taskExecutor">
 3             <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
 4                 <property name="corePoolSize" value="5"/>
 5                 <property name="keepAliveSeconds" value="3000"/>
 6                 <property name="maxPoolSize" value="50"/>
 7                 <property name="queueCapacity" value="200"/>
 8             </bean>
 9         </property>
10     </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

 1 @Component
 2 public class TestListener implements ApplicationListener<TestEvent> {
 3 
 4     @Async
 5     @Override
 6     public void onApplicationEvent(TestEvent testEvent) {
 7 
 8         TestParam param = (TestParam) testEvent.getSource();
 9         System.out.println(".......开始.......");
10         System.out.println("发送邮件:"+param.getEmail());
11         System.out.println(".......结束.....");
12     }
13 }

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

新建自定义EventHandler:

 1 @Component
 2 public class TestEventHandler {
 3 
 4     @Async
 5     @EventListener
 6     public void handleTestEvent(TestEvent testEvent) {
 7 
 8         TestParam param = (TestParam) testEvent.getSource();
 9         System.out.println(".......开始.......");
10         System.out.println("发送邮件:"+param.getEmail());
11         System.out.println(".......结束.....");
12     }
13

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

总结:

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

posted @ 2018-06-26 15:04  冬至饮雪  阅读(19665)  评论(3编辑  收藏  举报