基于Spring Boot应用ApplicationEvent案例场景

目录
  • 一、案例场景
  • 二、使用类
  • 三、代码
    • 1.事件对象
      • 1.1 ExampleApplicationEvent
      • 1.2 ExampleLocalApplicationEvent
      • 1.3 EventTypeEnum
    • 2.事件监听者
      • 2.1 IEventListener
      • 2.2 AbstractEventListener
      • 2.3 OrderEventListener
    • 3.事件发布者
      • 3.1 IEventPublisher
      • 3.2 LocalEventPublisher
    • 4.Restful请求触发事件
      • 4.1 EventController
      • 4.2 OrderInfo
      • 4.3 ResultObj
    • 5.测试
      • 5.1 请求信息
      • 5.2 日志

记录:276

场景:利用Spring的机制发布ApplicationEvent和监听ApplicationEvent。

版本:Spring Boot 2.6.3

一、案例场景

1.发起restful请求,根据请求参数发布不同的事件。

2.事件监听者,监听到事件后,做预定操作。

3.本例是事件同步处理机制,即发布事件后,会同步监听事件。

二、使用类

org.springframework.context.ApplicationEvent,spring的事件对象。

org.springframework.context.ApplicationListener,事件监听者接口。

org.springframework.context.ApplicationEventPublisher,事件发布者接口。

三、代码

1.事件对象

事件对象实现ApplicationEvent。

1.1 ExampleApplicationEvent

ExampleApplicationEvent,一个抽象类。继承ApplicationEvent,自定义拓展微服务中需求的一些属性。

public abstract class ExampleApplicationEvent extends ApplicationEvent {
  private static final String eventSource = "Example";
  private String eventType = null;
  private Object eventData = null;
  public ExampleApplicationEvent(Object eventData) {
      super(eventSource);
      this.eventData = eventData;
  }
  public ExampleApplicationEvent(Object eventData, String eventType) {
      super(eventSource);
      this.eventData = eventData;
      this.eventType = eventType;
  }
  public String getEventType() {
      return eventType;
  }
  public Object getEventData() {
      return eventData;
  }
}

1.2 ExampleLocalApplicationEvent

ExampleLocalApplicationEvent,是抽象类ExampleApplicationEvent的实现类,在此处按需拓展属性。

public class ExampleLocalApplicationEvent extends ExampleApplicationEvent {
  public ExampleLocalApplicationEvent(Object eventData) {
      super(eventData);
  }
  public ExampleLocalApplicationEvent(Object eventData, String eventType) {
      super(eventData, eventType);
  }
}

1.3 EventTypeEnum

EventTypeEnum,自定义事件类型枚举,按需扩展。

public enum EventTypeEnum {
  CHANGE("change", "变更事件"),
  ADD("add", "新增事件");
  private String id;
  private String name;
  public String getId() {
   return id;
  }
  public String getName() {
   return name;
  }
  EventTypeEnum(String id, String name) {
   this.id = id;
   this.name = name;
  }
  public static EventTypeEnum getEventTypeEnum(String id) {
   for (EventTypeEnum var : EventTypeEnum.values()) {
       if (var.getId().equalsIgnoreCase(id)) {
           return var;
       }
   }
   return null;
  }
}

2.事件监听者

事件监听者包括接口和抽象类。

2.1 IEventListener

IEventListener,一个接口,继承ApplicationListener接口。

@SuppressWarnings("rawtypes")
public interface IEventListener extends ApplicationListener {
}

2.2 AbstractEventListener

AbstractEventListener,一个抽象类,实现IEventListener接口。并提供抽象方法便于实现类扩展和代码解耦。

public abstract  class AbstractEventListener implements IEventListener {
 @Override
 public void onApplicationEvent(ApplicationEvent event){
  if(!(event instanceof ExampleApplicationEvent)){
    return;
  }
  ExampleApplicationEvent exEvent = (ExampleApplicationEvent) event;
  try{
    onExampleApplicationEvent(exEvent);
  }catch (Exception e){
    e.printStackTrace();
  }
 }
 protected abstract void onExampleApplicationEvent(ExampleApplicationEvent event);
}

2.3 OrderEventListener

OrderEventListener,实现类AbstractEventListener抽象类。监听事件,并对事件做处理,是一个业务类。

@Slf4j
@Component
public class OrderEventListener extends AbstractEventListener {
  @Override
  protected void onExampleApplicationEvent(ExampleApplicationEvent event) {
   log.info("OrderEventListener->onSpApplicationEvent,监听事件.");
   Object eventData = event.getEventData();
   log.info("事件类型: " + EventTypeEnum.getEventTypeEnum(event.getEventType()));
   log.info("事件数据: " + eventData.toString());
  }
}

3.事件发布者

事件监听者包括接口和实现类。

3.1 IEventPublisher

IEventPublisher,自定义事件发布接口,方便扩展功能和属性。

public interface IEventPublisher {
    boolean publish(ExampleApplicationEvent event);
}

3.2 LocalEventPublisher

LocalEventPublisher,事件发布实现类,此类使用@Component,spring的IOC容器会加载此类。此类调用ApplicationEventPublisher的publishEvent发布事件。

@Slf4j
@Component("localEventPublisher")
public class LocalEventPublisher implements IEventPublisher {
  @Override
  public boolean publish(ExampleApplicationEvent event) {
    try{
      log.info("LocalEventPublisher->publish,发布事件.");
      log.info("事件类型: " + EventTypeEnum.getEventTypeEnum(event.getEventType()));
      log.info("事件数据: " + event.getEventData().toString());
      SpringUtil.getApplicationContext().publishEvent(event);
    }catch (Exception e){
      log.info("事件发布异常.");
      e.printStackTrace();
      return false;
    }
    return true;
  }
}

4.Restful请求触发事件

使用Restful请求触发事件发生。

4.1 EventController

EventController,接收Restful请求。

@Slf4j
@RestController
@RequestMapping("/event")
public class EventController {
  @Autowired
  private LocalEventPublisher eventPublisher;
  @PostMapping("/f1")
  public Object f1(@RequestBody Object obj) {
   log.info("EventController->f1,接收参数,obj = " + obj.toString());
   Map objMap = (Map) obj;
   OrderInfo orderInfo = new OrderInfo();
   orderInfo.setUserName((String) objMap.get("userName"));
   orderInfo.setTradeName((String) objMap.get("tradeName"));
   orderInfo.setReceiveTime(DateUtil.format(new Date(),
           "yyyy-MM-dd HH:mm:ss"));
   String flag = (String) objMap.get("flag");
   if (StringUtils.equals("change", flag)) {
       eventPublisher.publish(new ExampleLocalApplicationEvent(orderInfo,
               EventTypeEnum.CHANGE.getId()));
   } else if (StringUtils.equals("add", flag)) {
       eventPublisher.publish(new ExampleLocalApplicationEvent(orderInfo,
               EventTypeEnum.ADD.getId()));
   } else {
       eventPublisher.publish(new ExampleLocalApplicationEvent(orderInfo));
   }
   log.info("EventController->f1,返回.");
   return ResultObj.builder().code("200").message("成功").build();
  }
}

4.2 OrderInfo

OrderInfo,数据对象,放入事件对象中传递。

@Data
@NoArgsConstructor
public class OrderInfo {
  private String userName;
  private String tradeName;
  private String receiveTime;
}

4.3 ResultObj

ResultObj,restful返回通用对象。

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ResultObj {
    private String code;
    private String message;
}

5.测试

5.1 请求信息

URL请求: http://127.0.0.1:8080/server/event/f1

入参:

{
    "userName": "HangZhou",
    "tradeName": "Vue进阶教程",
    "flag": "add"
}

返回值:

{
    "code": "200",
    "message": "成功"
}

5.2 日志

输出日志:

以上,感谢。

到此这篇关于基于Spring Boot应用ApplicationEvent的文章就介绍到这了,更多相关Spring Boot应用ApplicationEvent内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 详解SpringBoot 发布ApplicationEventPublisher和监听ApplicationEvent事件

    资料地址 Spring @Aync 实现方法 自定义需要发布的事件类,需要继承ApplicationEvent类或PayloadApplicationEvent<T>(该类也仅仅是对ApplicationEvent的一层封装) 使用@EventListener来监听事件 使用ApplicationEventPublisher来发布自定义事件(@Autowired注入即可) /** * 自定义保存事件 * @author peter * 2019/1/27 14:59 */ public cla

  • SpringBoot中ApplicationEvent和ApplicationListener用法小结

    目录 一.开发ApplicationEvent事件 二. 开发监听器 三.推送事件 四.注解方式实现监听器 对不起大家,昨天文章里的告别说早了,这个系列还不能就这么结束. 我们前面的文章中讲解过RabbitMQ的用法,所谓MQ就是一种发布订阅模式的消息模型.在Spring中其实本身也为我们提供了一种发布订阅模式的事件处理方式,就是ApplicationEvent和 ApplicationListener,这是一种基于观察者模式实现事件监听功能.也已帮助我们完成业务逻辑的解耦,提高程序的扩展性和可

  • 详解SpringBoot实现ApplicationEvent事件的监听与发布

    目录 新建SpringBoot项目 实现代码 pom.xml Application.java TaskPoolConfig.java EmailDto.java SendEmailEvent.java SendEmailListener.java SendEmailService.java SendEmailServiceImpl.java IndexController.java 通过发布订阅模式实现数据的异步处理,比如异步处理邮件发送 新建SpringBoot项目 项目结构 .├── po

  • 使用Spring的ApplicationEvent实现本地事件驱动的实现方法

    目录 一.介绍 二.使用示例 三.异步发布示例 四.在事务提交后发布事件示例 总结 一.介绍 Spring内置了简便的事件机制,可以非常方便的实现事件驱动,核心类包括 ApplicationEvent,具体事件内容,事件抽象基类,可继承该类自定义具体事件 ApplicationEventPublisher,事件发布器,可以发布ApplicationEvent,也可以发布普通的Object对象 ApplicationListener,事件监听器,可以使用注解@EventListener Trans

  • Spring Boot 发送邮件功能案例分析

    邮件服务简介 邮件服务在互联网早期就已经出现,如今已成为人们互联网生活中必不可少的一项服务.那么邮件服务是怎么工作的呢?如下给出邮件发送与接收的典型过程: 1.发件人使用SMTP协议传输邮件到邮件服务器A: 2.邮件服务器A根据邮件中指定的接收者,投送邮件至相应的邮件服务器B: 3.收件人使用POP3协议从邮件服务器B接收邮件. SMTP(Simple Mail Transfer Protocol)是电子邮件(email)传输的互联网标准,定义在RFC5321,默认使用端口25: POP3(Po

  • 基于Spring Boot的线程池监控问题及解决方案

    目录 前言 为什么需要对线程池进行监控 如何做线程池的监控 数据采集 数据存储以及大盘的展示 进一步扩展以及思考 如何合理配置线程池参数 如何动态调整线程池参数 如何给不同的服务之间做线程池的隔离 实现方案 前言 这篇是推动大家异步编程的思想的线程池的准备篇,要做好监控,让大家使用无后顾之忧,敬畏生产. 为什么需要对线程池进行监控 Java线程池作为最常使用到的并发工具,相信大家都不陌生,但是你真的确定使用对了吗?大名鼎鼎的阿里Java代码规范要求我们不使用 Executors来快速创建线程池,

  • 详解基于Spring Boot与Spring Data JPA的多数据源配置

    由于项目需要,最近研究了一下基于spring Boot与Spring Data JPA的多数据源配置问题.以下是传统的单数据源配置代码.这里使用的是Spring的Annotation在代码内部直接配置的方式,没有使用任何XML文件. @Configuration @EnableJpaRepositories(basePackages = "org.lyndon.repository") @EnableTransactionManagement @PropertySource("

  • 基于spring boot 的配置参考大全(推荐)

    如下所示: # =================================================================== # COMMON SPRING BOOT PROPERTIES # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # =============================

  • 详解基于Spring Boot/Spring Session/Redis的分布式Session共享解决方案

    分布式Web网站一般都会碰到集群session共享问题,之前也做过一些Spring3的项目,当时解决这个问题做过两种方案,一是利用nginx,session交给nginx控制,但是这个需要额外工作较多:还有一种是利用一些tomcat上的插件,修改tomcat配置文件,让tomcat自己去把Session放到Redis/Memcached/DB中去.这两种各有优缺,也都能解决问题. 但是现在项目全线Spring Boot,并不自己维护Tomcat,而是由Spring去启动Tomcat.这样就会有一

  • 基于spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate(详解)

    1.pom添加依赖 <!-- spring data jpa,会注入tomcat jdbc pool/hibernate等 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <

  • 基于Spring Boot不同的环境使用不同的配置方法

    spring 多文件配置: 1.properties文件 2.YAML文件 一.properties文件 在 Spring Boot 中, 多环境配置的文件名需要满足 application-{profile}. properties的格式, 其中{profile}对应你的环境标识, 如下所示. • application-dev.properties: 开发环境. • application-test.properties: 测试环境. • application-prod.propertie

  • 基于Spring Boot利用 ajax实现上传图片功能

    效果如下: 1.启动类中加入 SpringBoot重写addResourceHandlers映射文件路径 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/E/"); } 设置静态资源路径 2.   表单

  • spring boot 结合jsp案例详解

    这篇文章主要介绍了spring boot 结合jsp案例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- jstl是⼀

  • 基于spring boot 日志(logback)报错的解决方式

    记录一次报错解决方法: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<java.lang.String, java.lang.String>] org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'logging.le

随机推荐