詳解SpringBoot實(shí)現(xiàn)ApplicationEvent事件的監(jiān)聽與發(fā)布
通過發(fā)布訂閱模式實(shí)現(xiàn)數(shù)據(jù)的異步處理,比如異步處理郵件發(fā)送
新建SpringBoot項(xiàng)目
項(xiàng)目結(jié)構(gòu)
.
├── 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
實(shí)現(xiàn)代碼
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
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;
/**
* 線程池參數(shù)配置
**/
@EnableAsync
@Configuration
public class TaskPoolConfig {
/**
* 自定義線程池
**/
@Bean
public Executor taskExecutor() {
//返回可用處理器的Java虛擬機(jī)的數(shù)量 12
int i = Runtime.getRuntime().availableProcessors();
System.out.println("系統(tǒng)最大線程數(shù) : " + i);
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心線程池大小
executor.setCorePoolSize(16);
//最大線程數(shù)
executor.setMaxPoolSize(20);
//配置隊(duì)列容量,默認(rèn)值為Integer.MAX_VALUE
executor.setQueueCapacity(99999);
//活躍時(shí)間
executor.setKeepAliveSeconds(60);
//線程名字前綴
executor.setThreadNamePrefix("asyncServiceExecutor -");
//設(shè)置此執(zhí)行程序應(yīng)該在關(guān)閉時(shí)阻止的最大秒數(shù),以便在容器的其余部分繼續(xù)關(guān)閉之前等待剩余的任務(wù)完成他們的執(zhí)行
executor.setAwaitTerminationSeconds(60);
//等待所有的任務(wù)結(jié)束后再關(guān)閉線程池
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;
/**
* 事件監(jiān)聽器
*/
@Component
public class SendEmailListener implements ApplicationListener<SendEmailEvent> {
@Autowired
private SendEmailService sendEmailService;
@Async
@Override
public 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 {
@Override
public void sendEmail(EmailDto emailDto) {
try {
// 模擬耗時(shí)3秒
Thread.sleep(3 * 1000);
} catch (Exception e) {
System.out.println("Email發(fā)送異常");
}
System.out.println("Email發(fā)送成功 " + 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 {
@Autowired
private ApplicationEventPublisher publisher;
@GetMapping("/sendEmail")
public String sendEmail() {
EmailDto emailDto = new EmailDto();
emailDto.setEmail("tom@qq.com");
emailDto.setSubject("郵件標(biāo)題");
emailDto.setContent("郵件內(nèi)容");
// 發(fā)布事件
publisher.publishEvent(new SendEmailEvent(emailDto));
return "success";
}
}到此這篇關(guān)于詳解SpringBoot實(shí)現(xiàn)ApplicationEvent事件的監(jiān)聽與發(fā)布的文章就介紹到這了,更多相關(guān)SpringBoot ApplicationEvent事件監(jiān)聽發(fā)布內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于QueryWrapper,實(shí)現(xiàn)MybatisPlus多表關(guān)聯(lián)查詢方式
這篇文章主要介紹了關(guān)于QueryWrapper,實(shí)現(xiàn)MybatisPlus多表關(guān)聯(lián)查詢方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。2022-01-01
SpringBoot集成Nacos實(shí)現(xiàn)注冊中心與配置中心流程詳解
這篇文章主要介紹了SpringBoot集成Nacos實(shí)現(xiàn)注冊中心與配置中心流程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02
Spring Security基于JWT實(shí)現(xiàn)SSO單點(diǎn)登錄詳解
這篇文章主要介紹了Spring Security基于JWT實(shí)現(xiàn)SSO單點(diǎn)登錄詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
在SpringBoot中注入RedisTemplate實(shí)例異常的解決方案
這篇文章主要介紹了在SpringBoot中注入RedisTemplate實(shí)例異常的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
Java中如何計(jì)算一段程序的運(yùn)行時(shí)間
這篇文章主要介紹了Java中如何計(jì)算一段程序的運(yùn)行時(shí)間問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
基于idea 的 Java中的get/set方法之優(yōu)雅的寫法
這篇文章主要介紹了基于idea 的 Java中的get/set方法之優(yōu)雅的寫法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01
Springboot+WebSocket實(shí)現(xiàn)在線聊天功能
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議。這篇文章主要為大家介紹了如何利用Springboot和WebSocket實(shí)現(xiàn)在線聊天功能,感興趣的小伙伴可以了解一下2023-02-02
Java實(shí)戰(zhàn)之超市收銀管理系統(tǒng)的實(shí)現(xiàn)
這篇文章主要介紹了如何利用Java實(shí)現(xiàn)超市收銀管理系統(tǒng),文中采用的技術(shù)有:Spring、SpringMVC、MyBatis、ThymeLeaf等,需要的可以參考一下2022-03-03
spring基于通用Dao的多數(shù)據(jù)源配置詳解
這篇文章主要為大家詳細(xì)介紹了spring基于通用Dao的多數(shù)據(jù)源配置,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下解2018-03-03
Java實(shí)現(xiàn)調(diào)用ElasticSearch?API的示例詳解
這篇文章主要為大家詳細(xì)介紹了Java調(diào)用ElasticSearch?API的效果資料,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,感興趣的可以了解一下2023-03-03

