发送邮件与撤回邮件的实现与详解
在现代应用中,邮件的发送往往需要处理复杂的业务逻辑,尤其是用户对此邮件的即时反馈和可撤回性。为了解决邮件不可撤回的问题,我们可以通过异步延时发送邮件的方式来实现。在这篇博客中,我将详细介绍如何使用线程池和延时任务来实现这一功能。
请注意,涉及收费内容!
1. 业务背景
众所周知,电子邮件一旦发送,无法直接撤回。为了解决这一问题,我们可以采用延时发送的方式。在发送邮件前,系统会设置一个延时(例如3分钟),在此期间,用户可以选择撤回邮件。如果在此时间段内用户撤回邮件,系统则不会执行实际的发送操作。
2. 线程池配置
以下是项目配置文件 application.yml
的示例配置:
task:
pool:
enabled: true
core-pool-size: 7 # cpu core + 1
max-pool-size: 13 # core * 2 + 1
keep-alive-seconds: 20
queue-capacity: 10
thread-name-prefix: Techik-
thread-group-name: Group-association
mail:
host: smtp.qiye.163.com
password: xxxxxxx
username: xxxxxxxxx
port: 465
default-encoding: UTF-8
protocol: smtp
properties:
mail.smtp.auth: true
mail.smtp.starttls.enable: false
mail.smtp.starttls.required: false
mail.smtp.socketFactory.port: 465
mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback: false
mail.smtp.timeout: 60000
mail.smtp.connectionTimeout: 5000
在 Spring 中,我们通过配置线程池来实现异步任务的处理。以下是线程池的配置类 TaskThreadPoolConfig
,它实现了异步任务的线程池和延时任务的线程池:
package com.techik.Config;
import com.techik.Model.properties.TaskThreadPoolProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import