异步任务
异步处理还是非常常用的,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。
同步等待的情况
1、创建一个service包,创建一个类AsyncServic
package com.yaya.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* * @author Allein
* * @date 2021/7/28 16:25
*
*/
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
}
2、编写controller包,编写AsyncController类
package com.yaya.controller;
import com.yaya.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* * @author Allein
* * @date 2021/7/28 16:26
*
*/
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();
return "ok";
}
}
3、访问http://localhost:8080/hello进行测试,3秒后出现ok
异步处理
如果想让用户直接得到消息,就在后台使用多线程的方式进行处理
4、给hello方法添加@Async注解
@Service
public class AsyncService {
//告诉Spring这是一个异步方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
}
5、主程序上添加@EnableAsync注解
SpringBoot就会自己开一个线程池,进行调用!但是要让这个注解生效,我们还需要在主程序上添加一个注解@EnableAsync ,开启异步注解功能;
package com.yaya;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class Springboot08TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot08TestApplication.class, args);
}
}
6、重启测试,网页瞬间响应,后台代码依旧执行!
定时任务
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,Spring为我们提供了异步执行任务调度的方式,提供了两个接口。
- TaskExecutor接口
- TaskScheduler接口
两个注解:
- @EnableScheduling
- @Scheduled
cron表达式
cron:计划任务,是任务在约定的时间执行已经计划好的工作,这是表面的意思。在Linux中,我们经常用到 cron 服务器来完成这项工作。cron服务器可以根据配置文件约定的时间来执行特定的任务。
结构
corn从左到右(用空格隔开):秒 分 小时 月份中的日期 月份 星期中的日期 年份
各字段的含义
字段 | 允许值 | 允许的特殊字符 |
---|---|---|
秒(Seconds) | 0~59的整数 | , - * / 四个字符 |
分(Minutes) | 0~59的整数 | , - * / 四个字符 |
小时(Hours) | 0~23的整数 | , - * / 四个字符 |
日期(DayofMonth) | 1~31的整数(但是你需要考虑你月的天数) | ,- * ? / L W C 八个字符 |
月份(Month) | 1~12的整数或者 JAN-DEC | , - * / 四个字符 |
星期(DayofWeek) | 1~7的整数或者 SUN-SAT (1=SUN) | , - * ? / L C # 八个字符 |
常用表达式例子
(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触发
测试
创建ScheduledService.java
1、创建一个ScheduledService,里面存在一个hello方法,定时执行该方法
package com.yaya.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
* * @author Allein
* * @date 2021/7/28 17:10
*
*/
@Service
public class ScheduleService {
/*
30 15 10 * * ? 每天10点5分30秒执行执行一次
30 0/5 10,18 * * ? 每天10点和18点,每隔五分钟执行一次
0 15 10 ? * 1-6 每个月的周一到周六10.15分执行一次
* 表示匹配任意字符
多个值用,隔开
*/
//在特定的时间执行这个方法
//cron表达式
//秒 分 时 日 月 周几(0-7)
@Scheduled(cron = "30 15 10 * * ?")
public void hello(){
System.out.println("hello,你被执行了...");
}
}
主程序上增加@EnableScheduling
2、写完定时任务之后,我们需要在主程序上增加@EnableScheduling 开启定时任务功能
@EnableAsync //开启异步注解功能
@EnableScheduling //开启定时功能注解
@SpringBootApplication
public class Springboot08TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot08TestApplication.class, args);
}
}
邮件任务
引入maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置文件
spring.mail.username=1668449199@qq.com
#QQ授权码
spring.mail.password=xxqhzgcpwbzgehbf
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
获取QQ授权码
获取授权码:在QQ邮箱中的设置->账户->开启pop3和smtp服务
测试
package com.yaya;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class Springboot08TestApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//一个简单的邮件
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("学习发邮件");
mailMessage.setText("好好学习,天天向上!");
mailMessage.setTo("1668449199@qq.com");
mailMessage.setFrom("1668449199@qq.com");
mailSender.send(mailMessage);
}
@Test
void contextLoads1() throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//正文
helper.setSubject("好好学习");
helper.setText("<p style='color:red'>Study hard!!!</p>",true);
//附件
helper.addAttachment("1.jpg",new File("E:\\Pr\\素材\\pic\\1.jpg"));
helper.addAttachment("2.jpg",new File("E:\\Pr\\素材\\pic\\2.jpg"));
helper.setTo("1668449199@qq.com");
helper.setFrom("1668449199@qq.com");
mailSender.send(mimeMessage);
}
/**
* //实际开发中可以封装成一个方法...
* @param html 是否使用html
* @param subject 标题
* @param text 文本内容
* @throws MessagingException
*/
public void sendMail(Boolean html,String subject,String text) throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//正文
helper.setSubject(subject);
helper.setText(text,html);
//附件
helper.addAttachment("1.jpg",new File("E:\\Pr\\素材\\pic\\1.jpg"));
helper.addAttachment("2.jpg",new File("E:\\Pr\\素材\\pic\\2.jpg"));
helper.setTo("1668449199@qq.com");
helper.setFrom("1668449199@qq.com");
mailSender.send(mimeMessage);
}
}