SpringBoot 事件框架

说明:所有的代码基于SpringBoot 2.0.3版本

SpringBoot 事件架构

SpringBoot事件整体框架

SpringBoot整个事件框架由四部分组成:事件(Event)、事件发布者(Publisher)、事件分发器(dispatcher)和事件监听器(Listener)。

事件(Event)

事件是事件发布者和事件监听器之间通信的载体,事件本身包括事件发布者信息、具体事件信息,在事件的消费流程中事件是有方向的,事件只能从事件发布者流向事件监听器,事件不可以反向传播。

  • 事件继承关系
    SpringBoot中事件都直接或间接继承自Java的EventObject类。EventObject类主要定义了事件源“source”,所有的事件都包含source的引用,source是最初产生事件的对象。ApplicationEvent是SpringBoot框架中的事件基类,系统预置事件和自定义事件必须继承ApplicationEvent.
  • 自定义事件
    通过继承ApplicationEvent可以轻松自定义事件。在自定义事件中可以根据业务需要添加必要的字段来详细的描述事件本身,方便事件监听者获取事件信息并根据信息做出响应。
    UserEvent.class
import org.springframework.context.ApplicationEvent;

public class UserEvent extends ApplicationEvent {
    private final String action;
    private final String userName;

    public UserEvent(Object source, String action, String userName) {
        super(source);
        this.action = action;
        this.userName = userName;
    }

    public String getAction() {
        return action;
    }

    public String getUserName() {
        return userName;
    }
}
  • 系统事件
    SpringBoot已经预置了多个与应用生命周期绑定的事件,下面将按照事件发生的先后顺序简单介绍
    • ApplicationStartingEvent
      Spring Application启动事件。事件产生的时机为ApplicationListeners注册之后,Environment或ApplicationContext可用之前,事件源为Spring Application自身,ApplicationStartingEvent在生命周期过程中可能会被修改,请谨慎使用。
    • ApplicationEnvironmentPreparedEvent
      事件产生的时机为Spring Application已经启动,Environment第一次可用。
    • ApplicationPreparedEvent
      事件产生的时机为Spring Application已经启动,Application Context已经完全准备好但是还没有进行刷新,在该阶段已经开始加载Bean定义并且Environment已经完全可用。
    • ApplicationStartedEvent
      事件产生的时机为Application Context已经完成刷新,ApplicationRunner application和CommandLineRunner调用之前。
    • ApplicationReadyEvent
      Spring Application已经准备好对外提供服务。
    • ApplicationFailedEvent
      应用启动失败

事件发布者(Publisher)

事件的发布主体,Publisher通过事件向事件监听器(Listener)发送信息触发业务处理逻辑。在SpringBoot中,事件的发布者通常为xxxContext,在SpringBoot的框架中Context有“父子”关系,子Contenxt发布的事件,父Context会重复发布一次,事件会被重复消费,如果对应的处理逻辑有副作用,则会影响业务的正确性,在使用的时候一定要根据自己的业务选择合适的Context发布事件。

事件分发器(dispatcher)

事件分发器的主要职责是:将事件准确的分发给该事件的监听器。通常事件分发器需要维护一个事件到监听器之间的映射关系,以方便快速、准确的分发事件。很多框架的事件分发机制都是通过类似的原理实现,比如Zookeeper,Java NIO中的WatchService,Apache Commons FileAlterationListener接口等。SpringBoot中的事件分发器的接口为ApplicationEventMulticaster,该接口共有7个方法,按照功能可以分为三类:增加监听器、移除监听器、事件多播

  • 增加监听器
void addApplicationListener(ApplicationListener<?> listener)
void addApplicationListenerBean(String listenerBeanName)
  • 移除监听器
void removeApplicationListener(ApplicationListener<?> listener)
void removeApplicationListenerBean(String listenerBeanName)
void removeAllListeners()
  • 事件多播
void multicastEvent(ApplicationEvent event)
void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType)

事件监听器(Listener)

事件监听器是对特定事件感兴趣的对象,在收到感兴趣的事件后通常执行特定的业务逻辑,从而达到业务流程或代码架构解耦的效果。

监听器的实现

  • 实现ApplicationListener接口
    接口只有一个方法用于在事件发生时执行特定的业务逻辑,一个简单的UserEvent事件监听器如下
import org.springframework.context.ApplicationListener;
@Component
public class UserEventService implements ApplicationListener<UserEvent> {
    @Override
    public void onApplicationEvent(UserEvent event) {
        System.out.println(event.getAction());
    }
}

一个监听器需要进行注册才能被dispatcher分发,在SpringBoot中注册监听器有两种方式,第一种调用SpringApplication的addListeners方法,第二种利用SpringBoot的自动管理Bean的功能,将监听器注册为一个普通的Bean,例子中使用第二种方法。

  • 使用@EventListener注解
import org.springframework.stereotype.Component;
@Component
public class UserEventListener {
    @EventListener
    public void execute(UserEvent event) {
        System.out.println("@"+event.getAction());
    }
}

异步调用

  • 自定义异步执行器Executor
    自定义异步执行器只需要实现AsyncConfigurer接口即可,同时可以自定义异常处理器,AsyncConfigurer如下
public interface AsyncConfigurer {
    @Nullable
    default Executor getAsyncExecutor() {
        return null;
    }
    @Nullable
    default AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

一个简单的实现如下:

@Configuration
@EnableAsync
public class AsyncConfigurerImpl implements AsyncConfigurer {
    private static final Logger log = LoggerFactory.getLogger(AsyncConfigurerImpl.class);
    ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("AsyncEexecutor-%d").build();

    @Override
    public Executor getAsyncExecutor() {
        Executor executor = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(), factory);
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
                log.error("async exception {},method {}, args {}", throwable.getMessage(), method.getName(), objects);
            }
        };
    }
}

必须同时添加注解@Configuration和@EnableAsync

  • 使用@Async开启方法异步调用
    在类或方法上添加注解@Async即可实现方法的异步调用
import org.springframework.context.ApplicationListener;
@Component
@Async
public class UserEventService implements ApplicationListener<UserEvent> {
    @Override
    public void onApplicationEvent(UserEvent event) {
        System.out.println(event.getAction());
    }
}

总结

SpringBoot的事件机制整体非常的简介上手容易,但是一不小心可能会出现事件重复发布重复消费的问题给业务带来损害,另外业务和SpringBoot紧耦合,如果业务需要迁移平台对应的业务流程需要整改,如果不想和框架紧耦合可以考虑使用Google Guava中的EventBus或按照框架自己实现也是非常简单的。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,860评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,936评论 6 342
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,003评论 3 119
  • 如果能去历史上的任何时间,你会选择去什么时候呢? 最近被问到这个问题,我有一点懵。因为从来没想过要回去改变自己的过...
    鱼鲜支阅读 950评论 16 27
  • 从今天开始叫我姐姐 我给你买大白兔 买薄荷糖买酸奶片 买一刻钟安魂曲 傍晚来时叫我洁洁 我戴上小白帽红手套 顺着丝...
    锄风少年阅读 259评论 1 3