異步任務(wù)、定時任務(wù)、郵件任務(wù)
一、異步任務(wù)
在Java應(yīng)用中,絕大多數(shù)情況下都是通過同步的方式來實現(xiàn)交互處理的;但是在處理與第三方系統(tǒng)交互的時候,容易造成響應(yīng)遲緩的情況,之前大部分都是使用多線程來完成此類任務(wù),其實,在Spring 3.x之后,就已經(jīng)內(nèi)置了@Async來完美解決這個問題。
兩個注解:
@EnableAysnc、@Aysnc
二、定時任務(wù)
項目開發(fā)中經(jīng)常需要執(zhí)行一些定時任務(wù),比如需要在每天凌晨時候,分析一次前一天的日志信息。Spring為我們提供了異步執(zhí)行任務(wù)調(diào)度的方式,提供TaskExecutor 、TaskScheduler 接口。?
兩個注解:@EnableScheduling、@Scheduled
cron表達(dá)式:

image.png
@Service
public class ScheduledService {
/**
* second(秒), minute(分), hour(時), day of month(日), month(月), day of week(周幾).
* 0 * * * * MON-FRI
* 【0 0/5 14,18 * * ?】 每天14點整,和18點整,每隔5分鐘執(zhí)行一次
* 【0 15 10 ? * 1-6】 每個月的周一至周六10:15分執(zhí)行一次
* 【0 0 2 ? * 6L】每個月的最后一個周六凌晨2點執(zhí)行一次
* 【0 0 2 LW * ?】每個月的最后一個工作日凌晨2點執(zhí)行一次
* 【0 0 2-4 ? * 1#1】每個月的第一個周一凌晨2點到4點期間,每個整點都執(zhí)行一次;
*/
// @Scheduled(cron = "0 * * * * MON-SAT")
//@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
// @Scheduled(cron = "0-4 * * * * MON-SAT")
@Scheduled(cron = "0/4 * * * * MON-SAT") //每4秒執(zhí)行一次
public void hello(){
System.out.println("hello ... ");
}
}
三、郵件任務(wù)
- 郵件發(fā)送需要引入spring-boot-starter-mail
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- Spring Boot 自動配置MailSenderAutoConfiguration
@EnableAsync //開啟異步注解功能
@EnableScheduling //開啟基于注解的定時任務(wù)
@SpringBootApplication
public class Springboot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04TaskApplication.class, args);
}
}
- 定義MailProperties內(nèi)容,配置在application.yml中
spring.mail.username=534096094@qq.com
spring.mail.password=gtstkoszjelabijb
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
- 自動裝配JavaMailSender
-
測試郵件發(fā)送
image.png
@Autowired
JavaMailSenderImpl mailSender;
@Test
public void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
//郵件設(shè)置
message.setSubject("通知-今晚開會");
message.setText("今晚7:30開會");
message.setTo("17512080612@163.com");
message.setFrom("534096094@qq.com");
mailSender.send(message);
}
@Test
public void test02() throws Exception{
//1、創(chuàng)建一個復(fù)雜的消息郵件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//郵件設(shè)置
helper.setSubject("通知-今晚開會");
helper.setText("<b style='color:red'>今天 7:30 開會</b>",true);
helper.setTo("17512080612@163.com");
helper.setFrom("534096094@qq.com");
//上傳文件
helper.addAttachment("1.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\1.jpg"));
helper.addAttachment("2.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\2.jpg"));
mailSender.send(mimeMessage);
}
注意:
在進(jìn)行測試的時候,需要獲取其驗證

image.png

image.png
順便說一下我的個人博客
天涯博客
謝謝!??!
