异步、定时、邮件任务
一、异步
1、创建service包
2、创建AsyncService
类
异步处理还是非常常用的,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。
编写方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况;
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理....");
}
}
3、创建controller包
4、编写AsyncController
类
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();//停止三秒
return "ok";
}
}
5、访问http://localhost:8080/hello进行测试,3秒后出现ok,这是同步等待的情况。
6、给hello方法添加@Async注解
@Service
public class AsyncService {
//告诉Spring 这是一个异步方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理....");
}
}
SpringBoot就会自己开一个线程池,进行调用!但是要让这个注解生效,我们还需要在主程序上添加一个注解**@EnableAsync** ,开启异步注解功能;
@EnableAsync //开启异步注解
@SpringBootApplication
public class Springboot08TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot08TestApplication.class, args);
}
}
7、重启测试,网页瞬间响应,后台代码依旧执行!
二、定时
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,Spring为我们提供了异步执行任务调度的方式,提供了两个接口。
- TaskExecutor接口
- TaskScheduler接口
两个注解:
- @EnableScheduling
- @Scheduled
cron表达式
字段 | 允许值 | 允许的特殊字符 |
---|---|---|
秒(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 # 八个字符 |
年(可选,留空)(Year) | 1970~2099 | , - * / 四个字符 |
特殊字符 | 代表含义 |
---|---|
, | 枚举 |
- | 区间 |
* | 任意 |
/ | 步长 |
? | 日/星期冲突匹配 |
L | 最后 |
W | 工作日 |
C | 和calendar联系后计算的值 |
# | 星期,4#2,第2个星期三 |
测试步骤:
1、创建一个ScheduledService
@Service
public class ScheduledService {
//特定时间执行这个方法 Timer
/*
0 35 9 * * ? 每天9点35分0秒时执行
0 0/5 10,18 * * ? 每天10点、18点,每隔五分钟执行一次
*/
//cron 表达式 秒 分 时 日 月 周几
@Scheduled(cron = "0 35 9 * * ?")
public void hello(){
System.out.println("hello,你被执行了");
}
}
2、 在主程序上增加@EnableScheduling 开启定时任务功能
@EnableScheduling //开启定时功能注解
@EnableAsync //开启异步注解
@SpringBootApplication
public class Springboot08TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot08TestApplication.class, args);
}
}
3、了解cron表达式
http://www.bejson.com/othertools/cron/
4、常用的表达式
(1)0/2 * * * * ? 表示每2秒 执行任务
(1)0 0/2 * * * ? 表示每2分钟 执行任务
(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触发
三、邮件
邮件发送,在日常开发中也是常用功能,Springboot也帮我们做了支持
- 邮件发送需要引入spring-boot-start-mail
- SpringBoot 自动配置MailSenderAutoConfiguration
- 定义MailProperties内容,配置在application.yml中
- 自动装配JavaMailSender
- 测试邮件发送
测试:
1、引入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
如果点进去可以看到它引入的依赖是
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>1.6.4</version>
<scope>compile</scope>
</dependency>
2、看源码,查找自动配置类MailSenderAutoConfiguration
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7Jcmyp1z-1605669708432)(C:\Users\wangqun\AppData\Roaming\Typora\typora-user-images\image-20201118111413340.png)]
由于没看到@Bean注入,继续点进去看这个@import的配置类MailSenderJndiConfiguration.class
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PeHkPrJ2-1605669708439)(C:\Users\wangqun\AppData\Roaming\Typora\typora-user-images\image-20201118111509880.png)]
发现这个实现类JavaMailSenderImpl
看看具体的properties 有哪些参数(这里只截图一部分)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XJ4eWfLk-1605669708440)(C:\Users\wangqun\AppData\Roaming\Typora\typora-user-images\image-20201118111629461.png)]
这样我们就知道我们可以配置那些文件了
3、配置properties
spring.mail.username=xxxxxxx@qq.com
spring.mail.password=你的qq授权码
spring.mail.host=smtp.qq.com
# qq需要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true
获取授权码:在QQ邮箱中的设置->账户->开启pop3和smtp服务
4、测试
@SpringBootTest
class Springboot08TestApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//简单邮件
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("小狂神你好啊");
mailMessage.setText("感谢你的狂神说Java系列课程");
mailMessage.setTo("1013893214@qq.com");
mailMessage.setFrom("1013893214@qq.com");
mailSender.send(mailMessage);
}
@Test
void contextLoads2() throws MessagingException {
sendMail("感谢你的狂神说Java系列课程","小狂神你好啊",true);
}
/**
* 封装发送邮件方法
* @param text 正文
* @param subject 标题
* @param multipart 是否支持多文件
*/
public void sendMail(String text, String subject,boolean multipart){
//复杂邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装 正文
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(mimeMessage,multipart);
helper.setSubject(subject);
//这里的true用来指定,是否支持html
helper.setText(text,true);
//附件
helper.addAttachment("a.jpg", new File("D:\\a.jpg"));
helper.setTo("1013893214@qq.com");
helper.setFrom("1013893214@qq.com");
} catch (MessagingException e) {
e.printStackTrace();
}
mailSender.send(mimeMessage);
}
}
查看邮箱,邮件接收成功!