ITPub博客

首页 > IT职业 > IT生活 > Spring消息机制

Spring消息机制

IT生活 作者:zl_king 时间:2021-09-09 10:13:34 0 删除 编辑

消息机制是使用消息通知的方式,解耦生产者与消费者。编程上体现的是职责分割,使得消息处理的扩展性得到增强,符合设计原则中的单一职责以及开闭原则。

图片描述


Spring的ApplicationListener接口

ApplicationListener是Spring应用监听器基础接口,是消费者需要实现,用来消费特定事件的,接口如下:

public interface ApplicationListener<E extends ApplicationEvent> 
extends EventListener {    /**
    * Handle an application event.
    * @param event the event to respond to
    */
    void onApplicationEvent(E event);
  }

如何使用

利用Spring消息机制进行业务处理,逻辑非常简单,只需要以下几个步骤:

  1. 定义事件消息,即需要发布的消息对象,例如:

public class ApplicationEventSimple extends ApplicationEvent
  1. 定义处理器,并声明能够处理的消息类型,即实现ApplicationListener接口,实现类被Spring托管后,会自动被识别,并加入到消息监听器集合中,使用实例:

@Componentpublic class DefaultListener implements ApplicationListener<ApplicationEventSimple>
  1. 发布消息,通过ApplicationContext.publishEvent(ApplicationEvent event)发布消息,Spring会自动找到对应的处理器进行处理。

Spring内置事件

Spring在容器启动阶段或者销毁阶段,提供了相关的事件通知,通过传递整个ApplicationContext,以便使用者在容器启停阶段能够植入自己的逻辑。

消息类的基类为:ApplicationContextEvent,具体实现有ContextStartedEvent(容器开始启动事件),ContextClosedEvent(容器关闭时事件),ContextRefreshedEvent(IOC容器启动完成事件),ContextStoppedEvent(容器停止事件)。

如果想要监听这些事件,只需要实现监听程序即可,我司RPC自动注册就是通过ContextRefreshedEvent消息的监听,然后处理的。



作者:关捷
链接:https://www.jianshu.com/p/d71ceaf7160e
新


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1567/viewspace-2818529/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    102
  • 访问量
    725