springboot事件监听器怎么使用
引导案例
下面看一个简单的案例,
@Configuration public class SelfBusiness { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SelfBusiness.class); context.getBean(MyService.class).doBusiness(); context.close(); } @Component static class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); @Autowired private ApplicationEventPublisher publisher; public void doBusiness (){ logger.debug("主线业务"); logger.debug("发送短信"); logger.debug("发送邮件"); } }
运行上面的代码,观察效果
结合输出结果,这这段代码要实现的逻辑是,在主线业务执行完成后,需要执行发短信,发邮件等操作,这样写也没毛病,但不够优雅,从后续的业务可扩展性上来讲,不够友好,如果后续主线业务执行完毕,还需再增加一个其他的审计操作,则需要新增代码逻辑,这就将主线业务和支线逻辑紧密的耦合了起来;
就是说,我们期待的效果是,主线业务根本不关心其他的业务操作,只需要完成自身的逻辑就ok了,这就需要使用到spring提供的事件监听器功能;
使用事件监听器改造过程
springboot(spring)的事件监听器使用主要有两种方式,通过实现ApplicationListener接口,另一个就是在类上添加 @EventListener 注解来实现,接下来将对这两种方式逐一说明;
一、通过实现ApplicationListener接口实现步骤
1、自定义一个事件类(对象),继承ApplicationEvent
static class MyEvent extends ApplicationEvent { public MyEvent(Object source) { super(source); } }
可以这么理解,在代码中,可能有很多种类型的事件,不同的业务对应着不同的事件,对于某个具体的监听器来说,它只想监听A这种类型的事件;
2、自定义业务类实现ApplicationListener 接口
@Data static class Params { private String id ; private String name; private String phone; } @Component static class SmsApplicationListener implements ApplicationListener<MyEvent> { private static final Logger logger = LoggerFactory.getLogger(SmsApplicationListener.class); @Override public void onApplicationEvent(MyEvent myEvent) { Object source = myEvent.getSource(); try { Params params = objectMapper.readValue(source.toString(), Params.class); logger.debug("userId : {}",params.getId()); } catch (JsonProcessingException e) { e.printStackTrace(); } logger.debug("执行 sms 发短信业务"); } } @Component static class EmailApplicationListener implements ApplicationListener<MyEvent> { private static final Logger logger = LoggerFactory.getLogger(SmsApplicationListener.class); @Override public void onApplicationEvent(MyEvent myEvent) { Object source = myEvent.getSource(); logger.debug("执行 email 发邮件业务"); } }
显然,这里的监听器要监听的事件类型,正是上面我们定义的MyEvent ,这样,当业务被触发的时候,就可以在onApplicationEvent中拿到传递过来的参数,从而执行发短信(发邮件)业务操作了
3、主线业务发布事件
@Component static class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); @Autowired private ApplicationEventPublisher publisher; public void doBusiness (){ Params params = new Params(); params.setId("001"); params.setName("xiaoma"); params.setPhone("133******"); logger.debug("主线业务"); try { publisher.publishEvent(new MyEvent(objectMapper.writeValueAsString(params))); } catch (JsonProcessingException e) { e.printStackTrace(); } //publisher.publishEvent(new MyEvent("MyService doBusiness()")); //logger.debug("发送短信"); //logger.debug("发送邮件"); } }
对主线业务来说,这时候就不再需要写发送短信或邮件逻辑了,只需要一个publisher将事件发布出去即可,如果需要传递参数,将参数一起传递过去
完整的代码
@Configuration public class SelfBusiness { private static ObjectMapper objectMapper = new ObjectMapper(); public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SelfBusiness.class); context.getBean(MyService.class).doBusiness(); context.close(); } @Data static class Params { private String id ; private String name; private String phone; } /** * 自定义事件对象 */ static class MyEvent extends ApplicationEvent { public MyEvent(Object source) { super(source); } } @Component static class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); @Autowired private ApplicationEventPublisher publisher; public void doBusiness (){ Params params = new Params(); params.setId("001"); params.setName("xiaoma"); params.setPhone("133******"); logger.debug("主线业务"); try { publisher.publishEvent(new MyEvent(objectMapper.writeValueAsString(params))); } catch (JsonProcessingException e) { e.printStackTrace(); } //publisher.publishEvent(new MyEvent("MyService doBusiness()")); //logger.debug("发送短信"); //logger.debug("发送邮件"); } } /** * 监听事件触发后要执行的业务 */ @Component static class SmsApplicationListener implements ApplicationListener{ private static final Logger logger = LoggerFactory.getLogger(SmsApplicationListener.class); @Override public void onApplicationEvent(MyEvent myEvent) { Object source = myEvent.getSource(); try { Params params = objectMapper.readValue(source.toString(), Params.class); logger.debug("userId : {}",params.getId()); } catch (JsonProcessingException e) { e.printStackTrace(); } logger.debug("执行 sms 发短信业务"); } } @Component static class EmailApplicationListener implements ApplicationListener { private static final Logger logger = LoggerFactory.getLogger(SmsApplicationListener.class); @Override public void onApplicationEvent(MyEvent myEvent) { Object source = myEvent.getSource(); logger.debug("执行 email 发邮件业务"); } } }
再次运行上面的代码,观察效果,可以看到,仍然能满足预期的效果
二、通过添加 @EventListener 注解来实现
这种方式不再需要实现ApplicationListener 接口,而是直接在监听类的方法上面添加 @EventListener注解即可,相对要简化了一些,下面直接贴出完整的代码
package com.congge.config; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Configuration public class SelfBusiness2 { private static ObjectMapper objectMapper = new ObjectMapper(); public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SelfBusiness2.class); context.getBean(MyService.class).doBusiness(); context.close(); } @Data static class Params { private String id ; private String name; private String phone; } /** * 自定义事件对象 */ static class MyEvent extends ApplicationEvent { public MyEvent(Object source) { super(source); } } @Component static class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); @Autowired private ApplicationEventPublisher publisher; public void doBusiness (){ Params params = new Params(); params.setId("001"); params.setName("xiaoma"); params.setPhone("133******"); logger.debug("主线业务"); try { publisher.publishEvent(new MyEvent(objectMapper.writeValueAsString(params))); } catch (JsonProcessingException e) { e.printStackTrace(); } } } @Component static class SmsListenerService { private static final Logger logger = LoggerFactory.getLogger(SmsListenerService.class); @EventListener public void smsListener(MyEvent myEvent){ Object source = myEvent.getSource(); try { SelfBusiness2.Params params = objectMapper.readValue(source.toString(), SelfBusiness2.Params.class); logger.debug("userId : {}",params.getId()); } catch (JsonProcessingException e) { e.printStackTrace(); } logger.debug("执行 sms 发短信业务"); } } @Component static class EmailListenerService { private static final Logger logger = LoggerFactory.getLogger(EmailListenerService.class); @EventListener public void emailListener(MyEvent myEvent){ Object source = myEvent.getSource(); try { SelfBusiness2.Params params = objectMapper.readValue(source.toString(), SelfBusiness2.Params.class); logger.debug("userId : {}",params.getId()); } catch (JsonProcessingException e) { e.printStackTrace(); } logger.debug("执行 email 发邮件业务"); } } }
运行上面的代码,观察效果,同样可以达到预期的效果
三、使用异步
更进一步来说,为了提升主线业务的逻辑执行效率,我们希望发布事件的业务逻辑异步执行,这个该如何做呢?
翻阅源码可以知道,ApplicationEventPublisher 默认发布事件时候采用单线程同步发送,如果需要使用异步,需要自定义 ThreadPoolTaskExecutor ,以及SimpleApplicationEventMulticaster ,因此我们只需要覆盖一下这两个组件的bean即可,在上面的业务类中将下面的这两个bean添加进去;
@Bean public ThreadPoolTaskExecutor executor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); return executor; } @Bean public SimpleApplicationEventMulticaster applicationEventMulticaster(ThreadPoolTaskExecutor executor) { SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster(); eventMulticaster.setTaskExecutor(executor); return eventMulticaster; }
这时候再次运行代码,反复运行多次,就可以看到效果
对比下上面单线程效果
以上是springboot事件监听器怎么使用的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Jasypt介绍Jasypt是一个java库,它允许开发员以最少的努力为他/她的项目添加基本的加密功能,并且不需要对加密工作原理有深入的了解用于单向和双向加密的高安全性、基于标准的加密技术。加密密码,文本,数字,二进制文件...适合集成到基于Spring的应用程序中,开放API,用于任何JCE提供程序...添加如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter2.1.1Jasypt好处保护我们的系统安全,即使代码泄露,也可以保证数据源的

使用场景1、下单成功,30分钟未支付。支付超时,自动取消订单2、订单签收,签收后7天未进行评价。订单超时未评价,系统默认好评3、下单成功,商家5分钟未接单,订单取消4、配送超时,推送短信提醒……对于延时比较长的场景、实时性不高的场景,我们可以采用任务调度的方式定时轮询处理。如:xxl-job今天我们采

一、Redis实现分布式锁原理为什么需要分布式锁在聊分布式锁之前,有必要先解释一下,为什么需要分布式锁。与分布式锁相对就的是单机锁,我们在写多线程程序时,避免同时操作一个共享变量产生数据问题,通常会使用一把锁来互斥以保证共享变量的正确性,其使用范围是在同一个进程中。如果换做是多个进程,需要同时操作一个共享资源,如何互斥呢?现在的业务应用通常是微服务架构,这也意味着一个应用会部署多个进程,多个进程如果需要修改MySQL中的同一行记录,为了避免操作乱序导致脏数据,此时就需要引入分布式锁了。想要实现分

springboot读取文件,打成jar包后访问不到最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

在Springboot+Mybatis-plus不使用SQL语句进行多表添加操作我所遇到的问题准备工作在测试环境下模拟思维分解一下:创建出一个带有参数的BrandDTO对象模拟对后台传递参数我所遇到的问题我们都知道,在我们使用Mybatis-plus中进行多表操作是极其困难的,如果你不使用Mybatis-plus-join这一类的工具,你只能去配置对应的Mapper.xml文件,配置又臭又长的ResultMap,然后再去写对应的sql语句,这种方法虽然看上去很麻烦,但具有很高的灵活性,可以让我们

SpringBoot和SpringMVC都是Java开发中常用的框架,但它们之间有一些明显的差异。本文将探究这两个框架的特点和用途,并对它们的差异进行比较。首先,我们来了解一下SpringBoot。SpringBoot是由Pivotal团队开发的,它旨在简化基于Spring框架的应用程序的创建和部署。它提供了一种快速、轻量级的方式来构建独立的、可执行

1、自定义RedisTemplate1.1、RedisAPI默认序列化机制基于API的Redis缓存实现是使用RedisTemplate模板进行数据缓存操作的,这里打开RedisTemplate类,查看该类的源码信息publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//声明了key、value的各种序列化方式,初始值为空@NullableprivateRedisSe

本文来写个详细的例子来说下dubbo+nacos+Spring Boot开发实战。本文不会讲述太多的理论的知识,会写一个最简单的例子来说明dubbo如何与nacos整合,快速搭建开发环境。
