Guava study notes-02. EventBus use

Guava study notes-02. EventBus use

Guava EventBus

EventBus is a publish-subscribe model of Guava. Let's look at a simple implementation first:

  1. Define a message passing object for Event
 public class TestEvent1 {
     private final int message;

    /** * Construction method* @param message */
     public TestEvent1(int message) {
         this.message = message;
       //System.out.println("TestEvent1 event message:"+message);

     public int getMessage() {
         return message;
  1. Define a Listener
 public class EventListener {
     public int lastMessage = 0;

     @Subscribe public void listen(TestEvent1 event) {
         lastMessage = event.getMessage();

     public int getLastMessage() {
         return lastMessage;
  1. Define a use
  public static void main(String[] args) {
    //1. Construct an event bus
     EventBus eventBus = new EventBus("test");

    //2. Construct an event listener
     EventListener listener = new EventListener();

    //3. Register the event listener on the event bus

    //4. The event bus publishes events and triggers the listener method TestEvent1(1));


The result of the operation is:


If multiple methods need to be called, just add an @Subscribeannotation to the new method .

    public void listen2(TestEvent1 event) {
        lastMessage = event.getMessage();

If you want to use asynchronous processing, you can use the AsyncEventBusspecific code:

AsyncEventBus eventBus = new AsyncEventBus (Executors.newFixedThreadPool(3));

Of course, you can also register multiple EventListeners.

  eventBus.register(new EventListener());
  eventBus.register(new EventListener2());

(End of this article)

Author: Fu Weibo passenger address: If you have any intellectual property rights, copyright issues or theory wrong, please correct me.

Reference: Guava study notes-02. EventBus usage-cloud + community-Tencent Cloud