SpringBoot异步、邮件、定时任务

一、异步任务

首先在service服务类上添加注解@Async,然后在Application启动类上添加@EnableAsync注解即可

二、邮件任务

1、引入maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、配置yml文件

spring:
  mail:
    # 邮件服务地址
    host: smtp.qq.com
    # 端口,可不写默认,QQ邮箱是465端口
    port: 465
    # 编码格式
    default-encoding: utf-8
    # 用户名
    username: xxx@qq.com
    # 授权码,就是我们刚才准备工作获取的代码
    password: xxxxxx
    # 其它参数
    properties:
      mail:
        smtp:
          # 如果是用 SSL 方式,需要配置如下属性,使用qq邮箱的话需要开启
          ssl:
            enable: true
            required: true
          # 邮件接收时间的限制,单位毫秒
          timeout: 10000
          # 连接时间的限制,单位毫秒
          connectiontimeout: 10000
          # 邮件发送时间的限制,单位毫秒
          writetimeout: 10000

这里需要注意开通POP3/SMTP服务,以QQ邮箱为例,首页->设置->账户找到POP3/SMTP服务并开启,开启后会获得一个password,而username就填你的邮箱地址
在这里插入图片描述

3、编写发送邮件服务类

服务类

@Service
public class MailService {
    private static final Logger logger = LoggerFactory.getLogger(MailService.class);

    @Autowired
    private JavaMailSender mailSender;

    // 这里发件人和配置文件写的要一样
    private static final String SENDER = "xxx@qq.com";

    /**
     * 发送普通邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendSimpleMailMessage(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(SENDER);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("邮件发送成功");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常!", e);
        }
    }

    /**
     * 发送 HTML 邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendMimeMessage(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SENDER);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            logger.info("邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送MimeMessage时发生异常!", e);
        }catch (Exception e){
            logger.error("邮件异常");
        }
    }

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件路径
     */
    public void sendMimeMessage(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SENDER);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            assert fileName != null;
            helper.addAttachment(fileName, file);

            mailSender.send(message);
            logger.info("邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送带附件的MimeMessge时发生异常!", e);
        }catch (Exception e){
            logger.error("邮件异常");
        }
    }

    /**
     * 发送带静态文件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param rscIdMap 需要替换的静态文件
     */
    public void sendMimeMessage(String to, String subject, String content, Map<String, String> rscIdMap) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SENDER);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            for (Map.Entry<String, String> entry : rscIdMap.entrySet()) {
                FileSystemResource file = new FileSystemResource(new File(entry.getValue()));
                helper.addInline(entry.getKey(), file);
            }
            mailSender.send(message);
            logger.info("邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送带静态文件的MimeMessage时发生异常!", e);
        }catch (Exception e){
            logger.error("邮件异常");
        }
    }
}


测试类

@SpringBootTest
public class SpringbootEmailDemoTests {

    @Autowired
    private MailService mailService;

    //要发送的地址
    private static final String TO = "xxx@qq.com";
    private static final String SUBJECT = "测试邮件";
    private static final String CONTENT = "test content";

    /**
     * 测试发送普通邮件
     */
    @Test
    public void sendSimpleMailMessage() {
        mailService.sendSimpleMailMessage(TO, SUBJECT, CONTENT);
    }

    /**
     * 测试发送html邮件
     */
    @Test
    public void sendHtmlMessage() {
        String htmlStr = "<p style='color:red'>很高兴认识你<p>";
        mailService.sendMimeMessage(TO, SUBJECT, htmlStr);
    }

    /**
     * 测试发送带附件的邮件
     */
    @Test
    public void sendAttachmentMessage()  {
        String filePath = "D:\\share\\菜单.pdf";

        mailService.sendMimeMessage(TO, SUBJECT, CONTENT, filePath);
    }

    /**
     * 测试发送带附件的邮件
     */
    @Test
    public void sendPicMessage()  {
        String htmlStr = "<html><body>测试:图片1 <br> <img src='cid:pic1'/> <br>图片2 <br> <img src='cid:pic2'/></body></html>";
        Map<String, String> rscIdMap = new HashMap<>(2);
        rscIdMap.put("pic1","D:\\share\\111.jpg");
        rscIdMap.put("pic2", "D:\\share\\111.jpg");
        mailService.sendMimeMessage(TO, SUBJECT, htmlStr, rscIdMap);
    }
}

三、定时任务

首先在主启动类上添加@EnableScheduling,之后在服务类上添加@Scheduled(cron="xxx"),例如@Scheduled(cron="0 * * * * 0-7"),cron顺序分别为秒,分,时,日,月,周几

cron在线生成网站

常用表达式例子

  1. 0 0 2 1 * ? * 表示在每月的1日的凌晨2点调整任务

  2. 0 15 10 ? * MON-FRI 表示周一到周五每天上午10:15执行作业

  3. 0 15 10 ? 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行作

  4. 0 0 10,14,16 * * ? 每天上午10点,下午2点,4点

  5. 0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时

  6. 0 0 12 ? * WED 表示每个星期三中午12点

  7. 0 0 12 * * ? 每天中午12点触发

  8. 0 15 10 ? * * 每天上午10:15触发

  9. 0 15 10 * * ? 每天上午10:15触发

  10. 0 15 10 * * ? * 每天上午10:15触发

  11. 0 15 10 * * ? 2005 2005年的每天上午10:15触发

  12. 0 * 14 * * ? 在每天下午2点到下午2:59期间的每1分钟触发

  13. 0 0/5 14 * * ? 在每天下午2点到下午2:55期间的每5分钟触发

  14. 0 0/5 14,18 * * ? 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发

  15. 0 0-5 14 * * ? 在每天下午2点到下午2:05期间的每1分钟触发

  16. 0 10,44 14 ? 3 WED 每年三月的星期三的下午2:10和2:44触发

  17. 0 15 10 ? * MON-FRI 周一至周五的上午10:15触发

  18. 0 15 10 15 * ? 每月15日上午10:15触发

  19. 0 15 10 L * ? 每月最后一日的上午10:15触发

  20. 0 15 10 ? * 6L 每月的最后一个星期五上午10:15触发

  21. 0 15 10 ? * 6L 2002-2005 2002年至2005年的每月的最后一个星期五上午10:15触发

  22. 0 15 10 ? * 6#3 每月的第三个星期五上午10:15触发

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值