Java:SpringBoot实现ApplicationEvent事件的监听和发布
创始人
2024-05-30 00:01:24
0

通过发布订阅模式实现数据的异步处理,比如异步处理邮件发送

新建SpringBoot项目

项目结构

.
├── pom.xml
└── src└── main├── java│   └── com│       └── example│           └── demo│               ├── Application.java│               ├── config│               │   └── TaskPoolConfig.java│               ├── controller│               │   └── IndexController.java│               ├── entity│               │   └── EmailDto.java│               ├── event│               │   └── SendEmailEvent.java│               ├── listener│               │   └── SendEmailListener.java│               └── service│                   ├── SendEmailService.java│                   └── impl│                       └── SendEmailServiceImpl.java└── resources├── application.yml├── static└── templates

pom.xml


4.0.0org.springframework.bootspring-boot-starter-parent2.7.7 com.exampledemo0.0.1-SNAPSHOTdemoDemo project for Spring Boot1.8org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-devtoolsruntimetrueorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-maven-pluginorg.projectlomboklombok

Application.java

package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

TaskPoolConfig.java

package com.example.demo.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;/*** 线程池参数配置**/
@EnableAsync
@Configuration
public class TaskPoolConfig {/*** 自定义线程池**/@Beanpublic Executor taskExecutor() {//返回可用处理器的Java虚拟机的数量 12int i = Runtime.getRuntime().availableProcessors();System.out.println("系统最大线程数  : " + i);ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();//核心线程池大小executor.setCorePoolSize(16);//最大线程数executor.setMaxPoolSize(20);//配置队列容量,默认值为Integer.MAX_VALUEexecutor.setQueueCapacity(99999);//活跃时间executor.setKeepAliveSeconds(60);//线程名字前缀executor.setThreadNamePrefix("asyncServiceExecutor -");//设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行executor.setAwaitTerminationSeconds(60);//等待所有的任务结束后再关闭线程池executor.setWaitForTasksToCompleteOnShutdown(true);return executor;}
}

EmailDto.java

package com.example.demo.entity;import lombok.Data;@Data
public class EmailDto {private String email;private String subject;private String content;
}

SendEmailEvent.java

package com.example.demo.event;import com.example.demo.entity.EmailDto;
import org.springframework.context.ApplicationEvent;/*** 自定义事件*/
public class SendEmailEvent extends ApplicationEvent {private EmailDto emailDto;public SendEmailEvent(EmailDto emailDto) {super(emailDto);this.emailDto = emailDto;}public EmailDto getEmailDto() {return this.emailDto;}
}

SendEmailListener.java

package com.example.demo.listener;import com.example.demo.entity.EmailDto;
import com.example.demo.event.SendEmailEvent;
import com.example.demo.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;/*** 事件监听器*/
@Component
public class SendEmailListener implements ApplicationListener {@Autowiredprivate SendEmailService sendEmailService;@Async@Overridepublic void onApplicationEvent(SendEmailEvent event) {EmailDto emailDto = event.getEmailDto();this.sendEmailService.sendEmail(emailDto);}
}

SendEmailService.java

package com.example.demo.service;import com.example.demo.entity.EmailDto;public interface SendEmailService {void sendEmail(EmailDto emailDto);
}

SendEmailServiceImpl.java

package com.example.demo.service.impl;import com.example.demo.entity.EmailDto;
import com.example.demo.service.SendEmailService;
import org.springframework.stereotype.Service;@Service
public class SendEmailServiceImpl implements SendEmailService {@Overridepublic void sendEmail(EmailDto emailDto) {try {// 模拟耗时3秒Thread.sleep(3 * 1000);} catch (Exception e) {System.out.println("Email发送异常");}System.out.println("Email发送成功 " + emailDto);}
}

IndexController.java

package com.example.demo.controller;import com.example.demo.entity.EmailDto;
import com.example.demo.event.SendEmailEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class IndexController {@Autowiredprivate ApplicationEventPublisher publisher;@GetMapping("/sendEmail")public String sendEmail() {EmailDto emailDto = new EmailDto();emailDto.setEmail("tom@qq.com");emailDto.setSubject("邮件标题");emailDto.setContent("邮件内容");// 发布事件publisher.publishEvent(new SendEmailEvent(emailDto));return "success";}
}

参考

  • Spring事件机制 ApplicationEventPublisher

相关内容

热门资讯

122.(leaflet篇)l... 听老人家说:多看美女会长寿 地图之家总目录(订阅之前建议先查看该博客) 文章末尾处提供保证可运行...
育碧GDC2018程序化大世界... 1.传统手动绘制森林的问题 采用手动绘制的方法的话,每次迭代地形都要手动再绘制森林。这...
育碧GDC2018程序化大世界... 1.传统手动绘制森林的问题 采用手动绘制的方法的话,每次迭代地形都要手动再绘制森林。这...
Vue使用pdf-lib为文件... 之前也写过两篇预览pdf的,但是没有加水印,这是链接:Vu...
PyQt5数据库开发1 4.1... 文章目录 前言 步骤/方法 1 使用windows身份登录 2 启用混合登录模式 3 允许远程连接服...
Android studio ... 解决 Android studio 出现“The emulator process for AVD ...
Linux基础命令大全(上) ♥️作者:小刘在C站 ♥️个人主页:小刘主页 ♥️每天分享云计算网络运维...
再谈解决“因为文件包含病毒或潜... 前面出了一篇博文专门来解决“因为文件包含病毒或潜在的垃圾软件”的问题,其中第二种方法有...
南京邮电大学通达学院2023c... 题目展示 一.问题描述 实验题目1 定义一个学生类,其中包括如下内容: (1)私有数据成员 ①年龄 ...
PageObject 六大原则 PageObject六大原则: 1.封装服务的方法 2.不要暴露页面的细节 3.通过r...
【Linux网络编程】01:S... Socket多进程 OVERVIEWSocket多进程1.Server2.Client3.bug&...
数据结构刷题(二十五):122... 1.122. 买卖股票的最佳时机 II思路:贪心。把利润分解为每天为单位的维度,然后收...
浏览器事件循环 事件循环 浏览器的进程模型 何为进程? 程序运行需要有它自己专属的内存空间࿰...
8个免费图片/照片压缩工具帮您... 继续查看一些最好的图像压缩工具,以提升用户体验和存储空间以及网站使用支持。 无数图像压...
计算机二级Python备考(2... 目录  一、选择题 1.在Python语言中: 2.知识点 二、基本操作题 1. j...
端电压 相电压 线电压 记得刚接触矢量控制的时候,拿到板子,就赶紧去测各种波形,结...
如何使用Python检测和识别... 车牌检测与识别技术用途广泛,可以用于道路系统、无票停车场、车辆门禁等。这项技术结合了计...
带环链表详解 目录 一、什么是环形链表 二、判断是否为环形链表 2.1 具体题目 2.2 具体思路 2.3 思路的...
【C语言进阶:刨根究底字符串函... 本节重点内容: 深入理解strcpy函数的使用学会strcpy函数的模拟实现⚡strc...
Django web开发(一)... 文章目录前端开发1.快速开发网站2.标签2.1 编码2.2 title2.3 标题2.4 div和s...