springboot 异步邮件服务
2023-09-14 09:02:29 时间
目标:springboot,使用异步方式后台发送邮件。
关键点:异步服务不能在同类里调用。
1、mail依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2、yml配置
spring:
mail:
host: smtp.126.com
port: 25
username: abc99@126.com
password: HXAABBCCBEJLSYPQ
properties:
mail:
debug: false
username:发件人邮件地址,
password:发件人邮箱密码或者授权码
3、代码实现
3.1 线程池准备
@Configuration @EnableAsync public class ThreadPoolConfig { @Bean("messageThread") public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 设置核心线程数 executor.setCorePoolSize(4); // 设置最大线程数 executor.setMaxPoolSize(8); // 设置队列容量 executor.setQueueCapacity(100); // 设置线程活跃时间(秒) executor.setKeepAliveSeconds(60); // 设置默认线程名称 executor.setThreadNamePrefix("com.wood.message-"); // 设置拒绝策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); return executor; } }
3.2 邮件服务
@Slf4j @Service public class MailServiceImpl implements MailService { @Resource private JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String sender; @Override @Async("messageThread") //对应线程池的bean,使用线程池实现异步调用 public void sendMail(List<SysUser> receivers, String subject, String content) {
// 获取收件人邮件地址数组 String[] receiverMails = receivers.stream().map(SysUser::getEmail).filter(StringUtils::isNotBlank).distinct().toArray(String[]::new); if(receiverMails.length<1) return; SimpleMailMessage message = new SimpleMailMessage();
// 邮件主题 message.setSubject(subject);
// 发件人 message.setFrom("邮件提醒<"+sender+">");
// 收件人数组 message.setTo(receiverMails);
// 发送日期 message.setSentDate(new Date());
// 正文 message.setText(content); javaMailSender.send(message); log.info("邮件提醒,收件人:"+ Arrays.toString(receiverMails)+",内容:"+content); } }
相关文章
- springboot集成swagger2,构建优雅的Restful API
- Springboot 之 解决IDEA读取properties配置文件的中文乱码问题
- 创建SpringBoot Web服务及注意事项
- intellij idea2021.2:创建一个springboot项目(springboot 2.5.4)
- springboot整合HttpAsyncClient简单实用
- 【SpringBoot笔记03】SpringBoot框架之读取配置文件属性的六种方式
- 【最全最详细】Jenkins+Docker 一键自动化部署 SpringBoot 项目
- 4种Springboot RestTemplate 服务里发送HTTP请求用法
- SpringBoot项目中Controller层代码编写规范整理
- springboot项目中关于时间类型转换的格式问题
- SpringBoot三种方式配置Alibaba Druid用于监控或者查看SQL状况:yml或properties配置;Java bean代码配置;注解配置 yml和properties的在线相互转换
- Springboot+Vue实现将图片和表单一起提交到后端,同时将图片地址保存到数据库、再次将存储的图片展示到前端vue页面
- Springboot集成Web service接口服务
- Springboot内置的工具类之ReflectionUtils
- SpringBoot中@Mapper和@Repository注解的区别
- SpringBoot最简单服务配置
- SpringBoot使用Websocket
- SpringBoot+Nacos+Dubbo+Gateway 微服务