EventBus、AsyncEventBus详解及使用案例

EventBus顾名思义,事件总线,是一个轻量级的发布/订阅模式的应用模式。相比于MQ更加简洁,轻量,它可以在一个小系统模块内部使用。如果你也对EventBus感兴趣,或者想知道什么是EventBus,那就跟我一起来吧,后面会手把手教你使用EventBus,接下来就跟我一起走进EventBus吧。

一、EventBus的介绍和使用场景

EventBus是google的Guava库中的一个处理组件间通信的事件总线,它基于发布/订阅模式,实现了多组件之间通信的解耦合,事件产生方和事件消费方实现解耦分离,提升了通信的简洁性。

为什么使用事件总线?

当一个事件的发生(事件产生方),需要触发很多事件(事件消费方)的时候,我们通常会在事件产生方中,分别的去调用那些事件消费方,这样往往是很浪费资源。事件的产生方与事件的消费方,产生了极大的耦合,如果我们要改动某一个事件消费方,我们很可能还要改动事件的产生方。

使用场景:在工作中,经常会遇见使用异步的方式来发送事件,或者触发另外一个动作:经常用到的框架是MQ(分布式方式通知)。如果是同一个jvm里面通知的话,就可以使用EventBus。由于EventBus使用起来简单、便捷,因此,工作中会经常用到。

二、EventBus的三个关键点

EventBus有三个关键要素:

1、事件(Event)

事件是EventBus之间相互通信的基本单位,一个Event可以是任何类型。对,没错,就是Object,只要你想将任意一个Bean作为事件,这个类不需要做任何改变,就可以作为事件Event。不过在项目中不会这么随便(除非对代码严谨度没什么要求。。),一般会定义特定的事件类,类名以Event作为后缀,里面定义一些变量或者函数等。

2、事件发布者(Publisher)

事件发布者,就是发送事件到EventBus事件总线的一方,事件发布者调用Post()方法,将事件发给EventBus。你可以在程序的任何地方,调用EventBus的post()方法,发送事件给EventBus,由EventBus发送给订阅者们。

3、事件订阅者(Subscriber)

事件订阅者,就是接收事件的一方,这些订阅者需要在自己的方法上,添加@Subscribe注解声明自己为事件订阅者。不过只声明是不够的,还需要将自己所在的类,注册到EventBus中,EventBus才能扫描到这个订阅者。

三、手动实现EventBus和AsyncEventBus案例

<dependency>        <groupId>com.google.guava</groupId>        <artifactId>guava</artifactId>        <version>28.0-jre</version> </dependency>

其次看下本案例目录结构:

目录结构介绍:

event:一个自定义的事件类,类的内容随意定义。

eventListeners:定义了两个事件监听者类,类里面的方法加@Subscribe注解。

util:eventBus工具类。

TestMain类,测试函数。

本案例在EventBusUtil工具类中声明了EventBus和AsyncEventBus两个变量,因此,在后面演示AsyncEventBus的使用时,只需要更改TestMain中的post()方法即可。

下面逐一上代码。

CustomEvent类代码

package TestEventBus.event;public class CustomEvent {
    private int age;    public CustomEvent(int age){
   
           this.age = age;    }    public int getAge(){
   
           return this.age;    }}

EventListener1.java类代码

package TestEventBus.eventListeners;import TestEventBus.event.CustomEvent;import com.google.common.eventbus.Subscribe;import java.time.Instant;/** * @author fengjiale * @create 2019-09-04 13:40 * @desc 事件监听 **/public class EventListener1 {
   
       @Subscribe    public void test1(CustomEvent event){
   
           System.out.println(Instant.now() +"监听者1-->订阅者1,收到事件:"+event.getAge()+",线程号为:"+Thread.currentThread().getName());        try {
   
               Thread.sleep(3000);        } catch (InterruptedException e) {
   
               e.printStackTrace();        }    }    @Subscribe    public void test2(CustomEvent event){
   
           System.out.println(Instant.now() +"监听者1-->订阅者2,收到事件:"+event.getAge()+",线程号为:"+Thread.currentThread().getName());    }}

EventListener2.java类代码

package TestEventBus.eventListeners;import TestEventBus.event.CustomEvent;import com.google.common.eventbus.Subscribe;import java.time.Instant;import java.util.Date;/** * @author fengjiale * @create 2019-09-04 13:53 * @desc 事件监听 **/public class EventListener2 {
   
       @Subscribe    public void test(CustomEvent event){
   
           System.out.println(Instant.now() +",监听者2,收到事件:"+event.getAge()+",线程号为:"+Thread.currentThread().getName());        try {
   
               Thread.sleep(3000);        } catch (InterruptedException e) {
   
               e.printStackTrace();        }    }}

可以看到,两个监听者类,一共定义了三个订阅者,三个订阅者订阅的都是同一个事件对象。待会观察一下EventBus同步的方式下,收到事件之后订阅者们的处理方式。

工具类代码:

package TestEventBus.util; import com.google.common.eventbus.AsyncEventBus;import com.google.common.eventbus.EventBus;import java.util.concurrent.Executor;/** * @author fengjiale * @create 2019-09-04 13:55 * @desc 事件总线工具类 **/public class EventBusUtil {
   
       private static EventBus eventBus;    private static AsyncEventBus asyncEventBus;    private static Executor executor = new Executor() {
   
           public void execute(Runnable command) {
   
               new Thread(command).start();        }    };    //双重锁单例模式    private static AsyncEventBus getAsynEventBus(){
   
           if(asyncEventBus==null){
   
               synchronized (AsyncEventBus.class){
   
                   if(asyncEventBus==null){
   
                       asyncEventBus = new AsyncEventBus(executor);                }            }        }        return asyncEventBus;    }    //双重锁单例模式    private static EventBus getEventBus(){
   
           if(eventBus==null){
   
               synchronized (EventBus.class){
   
                   if(eventBus==null){
   
                       eventBus = new EventBus();                }            }        }        return eventBus;    }    public static void post(Object event){
   
           getEventBus().post(event);    }    //异步方式发送事件    public static void asyncPost(Object event){
   
           getAsynEventBus().post(event);    }    public static void register(Object object){
   
           getEventBus().register(object);        getAsynEventBus().register(object);    } }

测试类代码:

package TestEventBus; import TestEventBus.event.CustomEvent;import TestEventBus.eventListeners.EventListener1;import TestEventBus.eventListeners.EventListener2;import TestEventBus.util.EventBusUtil; import java.time.Instant; public class TestMain {
   
       public static void main(String[] args) {
   
           EventListener1 listener1 = new EventListener1();        EventListener2 listener2 = new EventListener2();        CustomEvent customEvent = new CustomEvent(23);        EventBusUtil.register(listener1);        EventBusUtil.register(listener2);        EventBusUtil.post(customEvent);        System.out.println(Instant.now() +",主线程执行完毕:"+Thread.currentThread().getName());    }}

上面是测试类,创建了事件监听者的对象,并且注册给了EventBus,调用EventBus的同步post方法执行。结果如下:

2019-09-04T09:05:35.420Z,监听者1-->订阅者1,收到事件:23,线程号为:main2019-09-04T09:05:38.480Z,监听者1-->订阅者2,收到事件:23,线程号为:main2019-09-04T09:05:38.480Z,监听者2,收到事件:23,线程号为:main2019-09-04T09:05:41.485Z,主线程执行完毕:main

同步EventBus总结规律:可以看到每一个事件的消费方在执行时,都是用的调用方的线程,并且同一时间只能同时执行一个订阅者的方法。从Listener1里的方法比Listener2里的方法先执行可以看出,先注册到EventBus的订阅者在收到事件后会先执行。

那么测试一下异步发送事件的结果,将上面注释打开,切换到EventBusUtil.asyncPost()方法,日志如下:

2019-09-04T09:12:14.010Z,监听者1-->订阅者2,收到事件:23,线程号为:Thread-22019-09-04T09:12:14.010Z,监听者2,收到事件:23,线程号为:Thread-32019-09-04T09:12:14.010Z,监听者1-->订阅者1,收到事件:23,线程号为:Thread-12019-09-04T09:12:24.014Z,主线程执行完毕:main

异步执行,三个订阅者同时执行,并且是为事件消费方重新开的一个新的线程去执行自己的任务,互相不等待。

这里由于并行执行,订阅者的方法中有sleep,因此也让主线程进行了10秒的等待。 

四、EventBus和AsyncEventBus使用区别

上面的测试案例简单,并且很能说明问题。

EventBus:同步事件总线

1.同步执行,事件发送方在发出事件之后,会等待所有的事件消费方执行完毕后,才会回来继续执行自己后面的代码。

2.事件发送方和事件消费方会在同一个线程中执行,消费方的执行线程取决于发送方。

3.同一个事件的多个订阅者,在接收到事件的顺序上面有不同。谁先注册到EventBus的,谁先执行,如果是在同一个类中的两个订阅者一起被注册到EventBus的情况,收到事件的顺序跟方法名有关。

AsyncEventBus:异步事件总线

1.异步执行,事件发送方异步发出事件,不会等待事件消费方是否收到,直接执行自己后面的代码。

2.在定义AsyncEventBus时,构造函数中会传入一个线程池。事件消费方收到异步事件时,消费方会从线程池中获取一个新的线程来执行自己的任务。

3.同一个事件的多个订阅者,它们的注册顺序跟接收到事件的顺序上没有任何联系,都会同时收到事件,并且都是在新的线程中,异步并发的执行自己的任务。

参考博客


猜你喜欢

转载自blog.csdn.net/CharlesYooSky/article/details/105812797