목차

Guava Event Bus

왜 필요한가

정리

public class EventBusBasicExample {
    private static final Logger log = LoggerFactory.getLogger(EventBusBasicExample.class);
 
    public static class MessageListener {
        @Subscribe
        public void receive(String message) throws InterruptedException {
            log.info("Receiving message... {}", message);
            receiving(3, message);
            log.info("Done");
        }
 
        private static void receiving(int count, String message) throws InterruptedException {
            for (int i = 0; i < count; i++) {
                log.info("... {}", message);
                TimeUnit.SECONDS.sleep(1L);
            }
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
        log.info("### Starting Event Bus ###");
        EventBus eventBus = new EventBus("sync");
        ExecutorService executor = Executors.newFixedThreadPool(5);
        AsyncEventBus asyncEventBus = new AsyncEventBus("async", executor);
 
        asyncEventBus.register(new MessageListener());
        eventBus.register(new MessageListener());
 
        asyncEventBus.post("ASYNC event"); // eventBus.post를 먼저 실행하면 블로킹됨.
        eventBus.post("SYNC event");
 
        log.info("### End ###");
 
        if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
            executor.shutdown();
        }
 
    }
}

결과.. EventBusmain 쓰레드에서 AsyncEventBus는 쓰레드 풀(ExecutorService)에서 subscribe 메소드 처리

@AllowConcurrentEvents

DeadEvent 받기

@Subscribe
public void handleDeadEvent(DeadEvent deadEvent) {
    // do something
}

주의할 점