SpringBoot 异步 定时任务 邮件

springboot异步

一: 在 MyConfiguration.java 中开启注解

@Configuration//指明当前类是一个配置类;就是来替代之前的Spring配置文件
@EnableAsync//开启定时任务

public class MyConfiguration {
}

二: 在Service.java的方法上标注@Async

SpringBoot 定时任务

高频访问地址:

在线Cron表达式生成器==>http://cron.qqe2.com/

Cron表达式出现的顺序依次为:

字段

允许值

允许的特殊字符

0-59

, - * /

0-59

, - * /

小时

0-23

, - * /

日期

1-31

, - * ? / L W C

月份

1-12

, - * /

星期

0-7或SUN-SAT 0,7代表SUN , 1代表MON, 6代表SAT

, - * ? / L C #

 

特殊字符含意:

特殊字符

代表含义

举例

说明

,

枚举

 
0 0 1,2,3 * * ?
 
每天的1点,2点,3点执行一次

-

区间

 
0 0 2-4 * * ?
 
每天凌晨2点到4点期间,每个整点都执行一次;

*

任意

   

/

步长

 
0 0/5 14,18 * * ?
 
每天14点整,和18点整,每隔5分钟执行一次

?

代表未知,
日/星期冲突匹配
(即每4位和第6位不能同时为?未知)

 
0 0 1 1 * ?
0 0 1 ? * 1

  每月1号的1点执行
  每周一的1点执行

L

最后

 
0 0 2 ? * 6L
 
每个月的最后一个周六凌晨2点执行一次

W

工作日

 
0 0 2 LW * ?
 
每个月的最后一个工作日凌晨2点执行一次

C

和calendar联系后计算过的值

 未研究  

#

星期,4#2,第2个星期四

 
0 0 1 * * 4#2
 
每月的第二个星期4的1点执行一次

 

一: 在 MyConfiguration.java 中开启注解

@Configuration//指明当前类是一个配置类;就是来替代之前的Spring配置文件
@EnableScheduling//开启定时任务
public class MyConfiguration {
}

二: 在Service.java的方法上标注@Scheduled

/**
 * 定时任务类
 */
@Service
public class ScheduledTaskService {
    /*注解这是一个异步任务, 将无阻塞地返回结果*/

    /**
     * 在线Cron表达式地址: http://cron.qqe2.com/
     * 我的笔记地址:
     * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
     *
     * @Scheduled(cron = "0 * * * * MON-SAT")//每个月的
     * @Scheduled(cron = "0 0/5 14,18 * * ?")// 每天14点整,和18点整,每隔5分钟执行一次
     * @Scheduled(cron = "0 15 10 ? * 1-6")// 每个月的周一至周六10:15分执行一次
     * @Scheduled(cron = "0 0 2 ? * 6L")//每个月的最后一个周六凌晨2点执行一次
     * @Scheduled(cron = "0 0 2 LW * ?")//每个月的最后一个工作日凌晨2点执行一次
     * @Scheduled(cron = "0 0 2-4 * * ?")//每天凌晨2点到4点期间,每个整点都执行一次;
     * @Scheduled(cron = "0 0 1,2,3 * * ?")//每天的1点,2点,3点执行一次
     * @Scheduled(cron = "0 0 1 * * 4#2")//每月的第二个星期4的1点执行一次
     */
    @Scheduled(cron = "0 * * * * ?")  // 需要在 MyConfiguration.java中开启异步注解 @EnableScheduling
    public String doTask() {
        System.out.println("定时任务 started");
        for (int i = 1; i < 2; i++) {
            System.out.println("定时任务 working  " + i + " s");
        }
        System.out.println("定时任务 finished");
        return "ScheduledTaskService finished";
    }
}

SpringBoot 邮件

邮件发送机制: 发件人@qq.com --> qq邮箱服务器 --> 163邮箱服务器 --> 收件人@163.com

1. pom.xml引入依赖

        <!--邮件发送starter, 内部用的是javax.mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2.内部使用的是MailSenderAutoConfiguration自动配置类

MailSenderAutoConfiguration

@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })
public class MailSenderAutoConfiguration {

MailSenderPropertiesConfiguration

@Configuration
@ConditionalOnProperty(prefix = "spring.mail", name = "host")
class MailSenderPropertiesConfiguration {

   private final MailProperties properties;

   MailSenderPropertiesConfiguration(MailProperties properties) {
      this.properties = properties;
   }

   @Bean
   @ConditionalOnMissingBean
   public JavaMailSenderImpl mailSender() {
      JavaMailSenderImpl sender = new JavaMailSenderImpl();
      applyProperties(sender);
      return sender;
   }
......

在application.properties中mail属性

配置服务器地址,用户名,邮箱密码等

spring.mail.username=jianyuan_5731@qq.com
# POP3/SMTP服务  gaaolyyinjcqbhbc  ,  IMAP/SMTP服务 xyusabvixxdbjeh
spring.mail.password=xyusuoidbjeh
spring.mail.host=smtp.qq.com
# qq需要ssl支持,以前会报错,但现在就算没有也不会报错了
spring.mail.properties.mail.smtp.ssl.enable=true

自动包装JavaMailSender类

MailController.java

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@RequestMapping("/mail")
@Controller
public class MailController {
    private static final Logger logger = LoggerFactory.getLogger(MailController.class);

    @Autowired
    JavaMailSender javaMailSender;

    // address: http://localhost:8080/springbootdemo/mail/send?subject=hello&text=helloBeauty
    //@Async//如果可以就尽量开启异步发送
    @ResponseBody
    @RequestMapping("/send")
    public String mainSend(String subject , String text ,String from ) {
        //SimpleMailMessage用于发送纯文本信息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(subject);
        message.setText(text);
        message.setTo("1713930654@qq.com");//可以是字符串列表
        message.setFrom("jianyuan_5731@qq.com");//这里的setFrom一定要和application.properties中配置的username一致, 不然会报mail from address must be same as authorization user错误
        javaMailSender.send(message);

        return "mainSend邮件发送成功";
    }

    //address: http://localhost:8080/springbootdemo/mail/sendHtmlAndFile?subject=hello&text=helloBeauty
    //@Async//如果可以就尽量开启异步发送
    @ResponseBody
    @RequestMapping("/sendHtmlAndFile")
    public String mainHtmlAndFile(String subject , String text ) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        //包装MimeMessage和声明是multipart为 true 的邮件
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message,true);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText("<b style='color:red'>helloBoy</b>");
        mimeMessageHelper.setTo("1713930654@qq.com");
        mimeMessageHelper.setFrom("jianyuan_5731@qq.com");//mail from address must be same as authorization user
        //添加附件到message中
        mimeMessageHelper.addAttachment("shortMessage.txt",new File("D:\file\短信.txt"));
        mimeMessageHelper.addAttachment("beauty.jpg",new File("D:\file\妮诺.jpg"));
        javaMailSender.send(message);

        return "mainHtmlAndFile邮件发送成功";
    }
}
原文地址:https://www.cnblogs.com/whatlonelytear/p/10894025.html