環(huán)境: IDEA版本2017.3.1 x64芍耘, JDK1.8, SpringBoot2.1.1
異步任務(wù)
- 在需要開啟異步的服務(wù)加上注解:@Async
@Service
public class AsyncService {
//告訴SpringBoot這是一個(gè)異步任務(wù)熄阻,SpringBoot會自動開啟一個(gè)線程去執(zhí)行
@Async
public void testAsyncService(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("執(zhí)行異步成功");
}
}
- 在主配置類上添加開啟異步注解功能:@EnableAsync
@EnableAsync //開啟異步注解功能
public class SpringbootMybatisApplication {
定時(shí)任務(wù)
- 在需要開啟定時(shí)任務(wù)的服務(wù)上添加注解
@Scheduled(cron = "0 * * * * MON-SAT")
/* {秒數(shù)} {分鐘} {小時(shí)} {日期} {月份} {星期} {年份(可為空)}
* cron的六個(gè)符號分別對應(yīng)以上時(shí)間單位斋竞,空格隔開
* * 表示所有值;
* ? 表示未說明的值秃殉,即不關(guān)心它為何值坝初;
* - 表示一個(gè)指定的范圍;
* , 表示附加一個(gè)可能值钾军;
* / 符號前表示開始時(shí)間鳄袍,符號后表示每次遞增的值;
*/
@Service
public class ScheduledService {
@Scheduled(cron = "0 * * * * MON-SAT")
public void testSchedule(){
System.out.println("測試定時(shí)任務(wù)成功");
}
}
image
- 在主配置類上開啟定時(shí)任務(wù)注解功能:@EnableScheduling
郵件任務(wù)
- 引入郵件依賴組件
<!-- 引入郵件拗小,如果發(fā)現(xiàn)注入失敗,可以自行到maven官網(wǎng)下載jar放進(jìn)對應(yīng)文件夾 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
可能會產(chǎn)生的錯誤:注入失斢:摺(可以自行到maven官網(wǎng)下載jar放進(jìn)對應(yīng)文件夾):
image
-
郵箱開啟POP3/SMTP服務(wù)
image 在主配置文件(yml方式)中配置郵箱參數(shù)
spring:
mail:
username: yourqq@qq.com
password: xxxxxx //授權(quán)碼,在服務(wù)選項(xiàng)中獲取
host: smtp.qq.com //qq郵箱服務(wù)器
properties:
mail:
smtp:
ssl:
enable: true //開啟安全連接
- 測試郵件發(fā)送
@Autowired
JavaMailSenderImpl mailSender;
/**
* 創(chuàng)建簡單消息郵件
*/
@Test
public void testMail(){
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("這是主題");
message.setText("這是內(nèi)容");
//收件人
message.setTo("xxxxx@qq.com");
//發(fā)送人
message.setFrom("xxxxx@qq.com");
mailSender.send(message);
}
/**
* 創(chuàng)建復(fù)雜消息郵件
*/
@Test
public void testMail02() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("這是復(fù)雜消息郵件主題");
helper.setText("<b style='color:red;'>這是復(fù)雜消息郵件內(nèi)容</b>",true);
//添加附件1
helper.addAttachment("1.jpg",new File("E:\\desktop\\8234.jpg"));
//添加附件2
helper.addAttachment("2.docx",new File("E:\\desktop\\形勢與政策課作業(yè).docx"));
//收件人
helper.setTo("xxxx@qq.com");
//發(fā)送人
helper.setFrom("xxxxx@qq.com");
mailSender.send(mimeMessage);
}
測試成功
image
更多Spring Boot整合可瀏覽此博客:malizhi.cn