1. 程式人生 > >Spring的事件機制詳解

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事件機制能很好地幫助我們消除不同業務間的耦合關係,也可以提高執行效率,應該根據業務場景靈活選擇.