成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Spring Event 業務解耦神器,大大提高可擴展性,刷爆了!

系統
Spring 使用反射機制,獲取了所有繼承 ApplicationListener 接口的監聽器,在 Spring 初始化時,會把監聽器都自動注冊到注冊表中。

一、前言

ApplicationContext 中的事件處理是通過 ApplicationEvent 類和 ApplicationListener 接口提供的。如果將實現了 ApplicationListener 接口的 bean 部署到容器中,則每次將 ApplicationEvent 發布到ApplicationContext 時,都會通知到該 bean,這簡直是典型的觀察者模式。設計的初衷就是為了系統業務邏輯之間的解耦,提高可擴展性以及可維護性。

Spring 中提供了以下的事件:

二、ApplicationEvent 與 ApplicationListener 應用

1.實現

自定義事件類,基于 ApplicationEvent 實現擴展:

public class DemoEvent extends ApplicationEvent {
    private static final long serialVersionUID = -2753705718295396328L;
    private String msg;

    public DemoEvent(Object source, String msg) {
        super(source);
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

定義 Listener 類,實現 ApplicationListener接口,并且注入到 IOC 中。等發布者發布事件時,都會通知到這個bean,從而達到監聽的效果。

@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
    @Override
    public void onApplicationEvent(DemoEvent demoEvent) {
        String msg = demoEvent.getMsg();
        System.out.println("bean-listener 收到了 publisher 發布的消息: " + msg);
    }
}

要發布上述自定義的 event,需要調用 ApplicationEventPublisher 的 publishEvent 方法,我們可以定義一個實現 ApplicationEventPublisherAware 的類,并注入 IOC來進行調用:

@Component
public class DemoPublisher implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher applicationEventPublisher;

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

    public void sendMsg(String msg) {
        applicationEventPublisher.publishEvent(new DemoEvent(this, msg));
    }
}

客戶端調用 publisher:

@RestController
@RequestMapping("/event")
public class DemoClient implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @GetMapping("/publish")
    public void publish(){
        DemoPublisher bean = applicationContext.getBean(DemoPublisher.class);
        bean.sendMsg("發布者發送消息......");
    }
}

輸出結果:

bean-listener 收到了 publisher 發布的消息: 發布者發送消息......

2.基于注解

我們可以不用實現 AppplicationListener 接口 ,在方法上使用 @EventListener 注冊事件。如果你的方法應該偵聽多個事件,并不使用任何參數來定義,可以在 @EventListener 注解上指定多個事件。

重寫 DemoListener 類如下:

public class DemoListener {
    @EventListener(value = {DemoEvent.class, TestEvent.class})
    public void processApplicationEvent(DemoEvent event) {
        String msg = event.getMsg();
        System.out.println("bean-listener 收到了 publisher 發布的消息: " + msg);
    }
}

3.事件過濾

如果希望通過一定的條件對事件進行過濾,可以使用 @EventListener 的 condition 屬性。以下實例中只有 event 的 msg 屬性是 my-event 時才會進行調用。

@EventListener(value = {DemoEvent.class, TestEvent.class}, condition = "#event.msg == 'my-event'")
public void processApplicationEvent(DemoEvent event) {
     String msg = event.getMsg();
     System.out.println("bean-listener 收到了 publisher 發布的消息: " + msg);
 }

此時,發送符合條件的消息,listener 才會偵聽到 publisher 發布的消息。

bean-listener 收到了 publisher 發布的消息: my-event

4.異步事件監聽

前面提到的都是同步處理事件,那如果我們希望某個特定的偵聽器異步去處理事件,如何做?

使用 @Async 注解可以實現類內方法的異步調用,這樣方法在執行的時候,將會在獨立的線程中被執行,調用者無需等待它的完成,即可繼續其他的操作。

@EventListener
@Async
public void processApplicationEvent(DemoEvent event) {
    String msg = event.getMsg();
    System.out.println("bean-listener 收到了 publisher 發布的消息: " + msg);
}

使用異步監聽時,有兩點需要注意:

  • 如果異步事件拋出異常,則不會將其傳播到調用方。
  • 異步事件監聽方法無法通過返回值來發布后續事件,如果需要作為處理結果發布另一個事件,請插入 ApplicationEventPublisher 以手動發布事件

三、好處及應用場景

ApplicationContext 在運行期會自動檢測到所有實現了 ApplicationListener 的 bean,并將其作為事件接收對象。當我們與 spring 上下文交互觸發 publishEvent 方法時,每個實現了 ApplicationListener 的 bean 都會收到 ApplicationEvent 對象,每個 ApplicationListener 可以根據需要只接收自己感興趣的事件。

這樣做有什么好處呢?

在傳統的項目中,各個業務邏輯之間耦合性比較強,controller 和 service 間都是關聯關系,然而,使用 ApplicationEvent 監聽 publisher 這種方式,類間關系是什么樣的?我們不如畫張圖來看看。

DemoPublisher 和 DemoListener 兩個類間并沒有直接關聯,解除了傳統業務邏輯兩個類間的關聯關系,將耦合降到最小。這樣在后期更新、維護時難度大大降低了。

ApplicationEvent 使用觀察者模式實現,那什么時候適合使用觀察者模式呢?觀察者模式也叫 發布-訂閱模式,例如,微博的訂閱,我們訂閱了某些微博賬號,當這些賬號發布消息時,我們都會收到通知。

總結來說,定義對象間的一種一對多的依賴關系,當一個對象的狀態發生改變時,所有依賴于它的對象都得到通知并被自動更新,從而實現廣播的效果。

四、源碼閱讀

Spring中的事件機制流程:

  • ApplicationEventPublisher是Spring的事件發布接口,事件源通過該接口的pulishEvent方法發布事件
  • ApplicationEventMulticaster就是Spring事件機制中的事件廣播器,它默認提供一個SimpleApplicationEventMulticaster實現,如果用戶沒有自定義廣播器,則使用默認的。它通過父類AbstractApplicationEventMulticaster的getApplicationListeners方法從事件注冊表(事件-監聽器關系保存)中獲取事件監聽器,并且通過invokeListener方法執行監聽器的具體邏輯
  • ApplicationListener就是Spring的事件監聽器接口,所有的監聽器都實現該接口,本圖中列出了典型的幾個子類。其中RestartApplicationListnener在SpringBoot的啟動框架中就有使用
  • 在Spring中通常是ApplicationContext本身擔任監聽器注冊表的角色,在其子類AbstractApplicationContext中就聚合了事件廣播器ApplicationEventMulticaster和事件監聽器ApplicationListnener,并且提供注冊監聽器的addApplicationListnener方法

通過上圖就能較清晰的知道當一個事件源產生事件時,它通過事件發布器ApplicationEventPublisher發布事件,然后事件廣播器ApplicationEventMulticaster會去事件注冊表ApplicationContext中找到事件監聽器ApplicationListnener,并且逐個執行監聽器的onApplicationEvent方法,從而完成事件監聽器的邏輯。

來到ApplicationEventPublisher 的 publishEvent 方法內部:

protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
 if (this.earlyApplicationEvents != null) {
 this.earlyApplicationEvents.add(applicationEvent);
 }
 else {
  // 
  getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
 }
}

多播事件方法:

@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
 ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
 Executor executor = getTaskExecutor();
 // 遍歷所有的監聽者
 for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
  if (executor != null) {
   // 異步調用監聽器
   executor.execute(() -> invokeListener(listener, event));
  }
  else {
   // 同步調用監聽器
   invokeListener(listener, event);
  }
 }
}

invokeListener:

protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
 ErrorHandler errorHandler = getErrorHandler();
 if (errorHandler != null) {
  try {
   doInvokeListener(listener, event);
  }
  catch (Throwable err) {
   errorHandler.handleError(err);
  }
 }
 else {
  doInvokeListener(listener, event);
 }
}

doInvokeListener:

private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
 try {
  // 這里是事件發生的地方
  listener.onApplicationEvent(event);
 }
 catch (ClassCastException ex) {
  ......
 }
}

點擊 ApplicationListener 接口 onApplicationEvent 方法的實現,可以看到我們重寫的方法。

五、總結

Spring 使用反射機制,獲取了所有繼承 ApplicationListener 接口的監聽器,在 Spring 初始化時,會把監聽器都自動注冊到注冊表中。

Spring 的事件發布非常簡單,我們來總結一下:

  • 定義一個繼承 ApplicationEvent 的事件
  • 定義一個實現 ApplicationListener 的監聽器或者使用 @EventListener 監聽事件
  • 定義一個發送者,調用 ApplicationContext 直接發布或者使用 ApplicationEventPublisher 來發布自定義事件

最后,發布-訂閱模式可以很好的將業務邏輯進行解耦(上圖驗證過),大大提高了可維護性、可擴展性。

責任編輯:趙寧寧 來源: 技術老男孩
相關推薦

2023-05-17 15:53:21

2020-08-18 08:04:16

DubboSPI框架

2021-05-17 07:28:23

Spring可擴展性項目

2022-02-28 10:02:54

Linux技巧命令

2022-08-02 16:38:53

惡意軟件密碼

2024-03-17 20:01:51

2021-09-02 09:42:11

測試軟件可擴展性開發

2013-03-29 10:23:02

數據庫癌癥治療

2021-12-21 09:50:02

Java請求合并代碼

2025-05-20 07:13:22

Spring異步解耦Event

2012-06-04 11:04:46

虛擬化

2022-09-05 15:17:34

區塊鏈比特幣可擴展性

2022-07-13 08:36:57

MQ架構設計模式

2009-11-30 17:47:24

2010-02-26 15:07:20

WCF單例服務

2021-12-03 14:41:00

云存儲可擴展性存儲

2024-10-10 14:01:34

2021-09-09 08:23:11

Vue 技巧 開發工具

2016-10-13 14:38:51

OpenStack可擴展性IT人員

2021-12-09 05:36:16

云存儲可擴展性數據存儲云存儲
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 不用播放器看的av | 成人精品一区二区三区四区 | 91亚洲精| 黄网站免费在线看 | 久久久久香蕉视频 | 亚洲国产中文字幕 | 精品国产第一区二区三区 | 亚洲人成在线观看 | 欧美精品在欧美一区二区少妇 | 国产 日韩 欧美 在线 | 亚洲第1页 | 国精久久 | 国产一在线 | 一区二区精品 | 欧美日韩国产在线 | 亚洲国产精品久久久久秋霞不卡 | 成人视屏在线观看 | 中文字幕av网址 | 免费的av | 性生活毛片 | 国产乱码精品一区二区三区五月婷 | 在线观看成人 | www.成人在线视频 | 中文字幕精 | 久久久久久久久久影视 | 精品久久久久久亚洲精品 | 鸳鸯谱在线观看高清 | 亚洲一区二区视频在线播放 | 国产精品一区二区无线 | 一区二区精品电影 | 国产日韩欧美精品一区二区三区 | 久久精品欧美一区二区三区不卡 | 狠狠干狠狠操 | 国产成人精品一区二 | 一级a性色生活片久久毛片波多野 | 自拍在线| 欧美一级二级视频 | 日本福利一区 | 欧美视频网 | 久久久久亚洲精品 | 免费福利视频一区二区三区 |