1、异步任务
启动类上加上支持异步任务注解
@EnableAsync // 开启异步注解功能
@SpringBootApplication
public class Springboot09AsynEmailTaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09AsynEmailTaskApplication.class, args);
}
}
编写异步任务代码
@Service
public class AsynService {
@Async
public void asynTake() throws InterruptedException {
System.out.println("任务正在执行中...");
Thread.sleep(5000);
System.out.println("任务执行完毕!");
}
}
测试:
@RestController
public class AsynController {
@Autowired
AsynService asynService;
@RequestMapping("/hello")
public String hello() throws InterruptedException {
asynService.asynTake();
return "任务执行完毕!";
}
}
2、定时发送
启动类上加上支持定时任务注解
@EnableScheduling // 开启定时任务注解功能
@SpringBootApplication
public class Springboot09AsynEmailTaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09AsynEmailTaskApplication.class, args);
}
}
测试
@Service
public class ScheduledService {
/* cron表达式
* 秒 分 时 日 月 周几
* 每秒执行一次 cron = "0/1 * * * * ?"
*/
@Scheduled(cron = "0/10 * * * * ?")
public void scheduledTest() {
System.out.println("喵,你被执行了~");
}
}
3、邮件发送
导入jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
在springboot配置文件中加上邮件服务器具体信息
spring:
# 配置邮箱服务器信息
mail:
username: 2723217360@qq.com
password: yxtkamoezospdgje
host: smtp.qq.com
测试
@SpringBootTest
class Springboot09AsynEmailTaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
// 发送一个简单的邮件
@Test
void contextLoads() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
// 标题
mailMessage.setSubject("你好呀!");
// 内容
mailMessage.setText("谢谢你的帮助");
mailMessage.setTo("2723217360@qq.com");
mailMessage.setFrom("2723217360@qq.com");
mailSender.send(mailMessage);
}
// 发送一个带附件的邮件
@Test
void contextLoads2() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
// 标题
helper.setSubject("你好呀!");
// 内容
helper.setText("你想要的图片都在附件里。");
// 附件
helper.addAttachment("kda阿卡丽.jpg", new File("C:\\Users\\27232\\Pictures\\KDA\\kda阿卡丽.jpg"));
helper.addAttachment("卡莎.jpg", new File("C:\\Users\\27232\\Pictures\\KDA\\虚空之女 KDA ALL OUT.jpg"));
// 接收人
helper.setTo("1842022976@qq.com");
// 发送人
helper.setFrom("2723217360@qq.com");
mailSender.send(mimeMessage);
}
}