跳到主要內容

Guava - EventBus Basic Usage

Introduction

最近在看Domain Event的實作方式,剛好看到Teddy分享使用Guava的EventBus來處理事件的註冊與分派,於是花了一些時間實驗API的用法。以下內容分享給大家。Source code可以從link下載。

How to?

Event

我的範例事件為MJGotGodGuyCardEvent:

public class MJGotGodGuyCardEvent {
 
    private final String girlName;
 
    public MJGotGodGuyCardEvent(String girlName) {
        this.girlName = girlName;
    }
 
    public String getGirlName() {
        return girlName;
    }
 
}

Event Handler

我的事件處理者有兩個,第一個為MJGoToPronhub。需注意的是:

  • @Subscribe: 用以宣告處理函式,函式只允許一個參數,且要與Event物件相同。
  • @AllowConcurrentEvents: 用以告知EventBus此函式可以接受Concurrent存取,預設會使用循序方式存取此函式。

public class MJGoToPronhub {
    private static Logger logger = LoggerFactory.getLogger(MJGoToPronhub.class);
    private List<MJGotGodGuyCardEvent> receivedEvents = new CopyOnWriteArrayList<>();
 
    @AllowConcurrentEvents
    @Subscribe
    public void handle(MJGotGodGuyCardEvent event) {
        receivedEvents.add(event);
        logger.info("MJGoToPronhub due to {}", event.getGirlName());
    }
 
    public List<MJGotGodGuyCardEvent> getReceivedEvents(){
        return receivedEvents;
    }
 
}

另外一個實作內容類似,不做贅述,名稱為MJGoToWanhua。

EventBus

用法相當簡單,只要透過EventBus的register把處理物件進去後,在負責發送通知的client使用post即可“循序”的讓handler處理訊息:

public class TestEventBus {
 
    private EventBus eventBus = new EventBus();
 
    private MJGoToPronhub MJGoToPronhubHandler = new MJGoToPronhub();
    private MJGoToWanhua MJGoToWanhuaHandler = new MJGoToWanhua();
 
    private void thenTheHandlerShouldReceiveTheEvent() {
        assertEquals(1, MJGoToPronhubHandler.getReceivedEvents().size());
        assertEquals(1, MJGoToWanhuaHandler.getReceivedEvents().size());
    }
 
    private void givenEventBusRegisterTwoGoodHandler(EventBus eventBus) {
        eventBus.register(MJGoToPronhubHandler);
        eventBus.register(MJGoToWanhuaHandler);
    }
 
    @Test
    public void ShouldGetReceivedEventsWhenPostEventToHandlers() {
        givenEventBusRegisterTwoGoodHandler(eventBus);
        MJGotGodGuyCardEvent event = new MJGotGodGuyCardEvent("Nancy");
 
        eventBus.post(event);
 
        thenTheHandlerShouldReceiveTheEvent();
    }
}

AsyncEventBus

假如覺得循序處理太慢,可以使用AsyncEventBus,使用方法與EventBus相同,但它post是non-blocking的:

public class TestAsyncEventBus {
    private AsyncEventBus asyncEventBus = new AsyncEventBus(Executors.newCachedThreadPool());
 
    private MJGoToPronhub MJGoToPronhubHandler = new MJGoToPronhub();
    private MJGoToWanhua MJGoToWanhuaHandler = new MJGoToWanhua();
 
    private void thenTheHandlerShouldReceiveTheEvent() {
        assertEquals(1, MJGoToPronhubHandler.getReceivedEvents().size());
        assertEquals(1, MJGoToWanhuaHandler.getReceivedEvents().size());
    }
 
    private void givenEventBusRegisterTwoGoodHandler(EventBus eventBus) {
        eventBus.register(MJGoToPronhubHandler);
        eventBus.register(MJGoToWanhuaHandler);
    }
 
    private MJGotGodGuyCardEvent givenDelayedMJGotGodGuyCardEvent(CountDownLatch latch) {
        return new MJGotGodGuyCardEvent("Nancy") {
            @Override
            public String getGirlName() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    return super.getGirlName();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    latch.countDown();
                }
            }
        };
    }
 
    private void thenPostShouldBeNotBlocked(long startTime) {
        long afterTime = System.currentTimeMillis();
        assertTrue((afterTime-startTime)<1000);
    }
 
    private void thenPostShouldBeDoneWithParallel(long startTime, CountDownLatch latch) throws InterruptedException {
        latch.await();
        long afterTime = System.currentTimeMillis();
        assertTrue((afterTime-startTime)>1000);
    }
 
    @Test
    public void testAsyncEventBus() throws InterruptedException {
        givenEventBusRegisterTwoGoodHandler(asyncEventBus);
 
        CountDownLatch latch = new CountDownLatch(2);
        MJGotGodGuyCardEvent event = givenDelayedMJGotGodGuyCardEvent(latch);
 
        long startTime = System.currentTimeMillis();
        asyncEventBus.post(event);
 
        thenPostShouldBeNotBlocked(startTime);
        thenPostShouldBeDoneWithParallel(startTime, latch);
        thenTheHandlerShouldReceiveTheEvent();
    }
}

Notes

  • 我使用的guava版本為30.0-jre。
  • 預設情況下,Handler處理發生例外時,並不影響工作繼續進行。
  • 可以透過實做SubscriberExceptionHandler去達到自己的例外處理需求,可由constructor去注入。


留言

這個網誌中的熱門文章

PostgreSQL - Unattended installation on windows

Introduction 要將別人軟體包裝到自己軟體中,不可或缺的東西就是Unattended installation。以Unattended installation來說,我們可以選擇透過Installer的silent mode安裝,也可以透過把目標軟體做成portable的版本。本篇文章分享這兩種方法,教導大家如何將PostgreSQL透過Unattended installation方式安裝到目標系統成為service。 Note. 本篇以PostgreSQL 10.7為例。 Install with installer Tips 安裝程式或反安裝程式的參數,除了可以直接上官網搜尋Installation User Guide以外,也可以直接使用help參數查詢: postgresql- 10.7 - 2 -windows-x64.exe --help Windows安裝程式主要有EnterpriseDB與BigSQL兩種。BigSQL版本安裝元件是透過網路下載且支援參數不如EnterpriseDB版本多,以我們需求來說,我們傾向於使用EnterpriseDB版本。接下來分享給大家安裝與反安裝方法。 Installation @ echo off set INSTALL_DIR =C:\postgres10 set INSTALLER =postgresql- 10.7 - 2 -windows-x64.exe   rem options for installation set SSMDB_SERVICE =postgresql- 10 set MODE =--unattendedmodeui none --mode unattended   set DB_PASSWD =--superpassword postgres set DB_PORT =--serverport 5432   set SERVICE_NAME =--servicename % SSMDB_SERVICE %   set PREFIX =--prefix "%INSTALL_DIR%" set DATA_DIR =--datadir "%INSTALL_DIR%\data"   set OPTIONS =

How to install RIDE on Windows?

Introduction 多年沒在Windows上開發RobotFramework,趁著這次整理一下RIDE安裝方法。 目前RIDE最新版本與Python對應版本如下: (3.6 < python <= 3.11) Install current released version (2.0.8.1) with: pip install -U robotframework-ride 安裝Python 直接到Python官網找尋最新的3.11版本,我使用3.11.9: link 。安裝就是一直下一步而已。 安裝wxPython 每次安裝RIDE最困難的都是wxPython。看了一下 官網 描述,我就姑且相信一下: 接著進入下 載頁面 就有安裝教學。基本上就是到Python目錄下的Scripts直接執行以下command: pip install -U wxPython 安裝RIDE 接著就如RIDE官網所說,執行以下command: pip install -U robotframework-ride 啟動RIDE 直接在相同目錄下執行ride就可以啟動了,你也可以直接在桌面建ride連結,加快下次啟動時間。 沒想到這次這麼順利就安裝完成了。因為我是使用java去啟動robot framework,就不特別講要怎麼使用pip安裝robot framework了。

Hello World!

即將要搬家,因此舊網頁內容將慢慢轉移至Blogger。 如果要存取舊網頁,可以使用以下連結: https://wiki.tonylin.idv.tw/dokuwiki/doku.php