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();
         System.out.println("Message:"+lastMessage);
     }

     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
     eventBus.register(listener);

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

 }    
 

The result of the operation is:

    Message:1

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

    @Subscribe         
    public void listen2(TestEvent1 event) {
        lastMessage = event.getMessage();
        System.out.println("Message2:"+lastMessage);
    } 

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: http://blog.laofu.online If you have any intellectual property rights, copyright issues or theory wrong, please correct me.

Reference: https://cloud.tencent.com/developer/article/1584280 Guava study notes-02. EventBus usage-cloud + community-Tencent Cloud