環境: IDEA版本2017.3.1 x64, JDK1異步任務.8, SpringBoot2.1.1
在需要開啟異步的服務加上注解:@Async
@Servicepublic class AsyncService {? ? //告訴SpringBoot這是一個異步任務,SpringBoot會自動開啟一個線程去執行? ? @Async? ? public voidtestAsyncService(){? ? ? ? try {? ? ? ? ? ? Thread.sleep(3000);? ? ? ? } catch (InterruptedException e) {? ? ? ? ? ? e.printStackTrace();? ? ? ? }? ? ? ? System.out.println("執行異步成功");? ? }}
在主配置類上添加開啟異步注解功能:@EnableAsync
@EnableAsync? //開啟異步注解功能public class SpringbootMybatisApplication {
定時任務
在需要開啟定時任務的服務上添加注解@Scheduled(cron = "0 * * * * MON-SAT")
/* {秒數} {分鐘} {小時} {日期} {月份} {星期} {年份(可為空)}? ? *? cron的六個符號分別對應以上時間單位,空格隔開? ? *? * 表示所有值;? ? *? ? 表示未說明的值,即不關心它為何值;? ? *? - 表示一個指定的范圍;? ? *? , 表示附加一個可能值;? ? *? / 符號前表示開始時間,符號后表示每次遞增的值;? ? */@Servicepublic class ScheduledService {? ? @Scheduled(cron ="0 * * * * MON-SAT")? ? public voidtestSchedule(){? ? ? ? System.out.println("測試定時任務成功");? ? }}
在主配置類上開啟定時任務注解功能:@EnableScheduling
郵件任務
引入郵件依賴組件
? ? ? ? ? ? org.springframework.boot? ? ? ? ? ? spring-boot-starter-mail
可能會產生的錯誤:注入失?。梢宰孕械絤aven官網下載jar放進對應文件夾):
郵箱開啟POP3/SMTP服務
在主配置文件(yml方式)中配置郵箱參數
spring:? mail:? ? username: yourqq@qq.com? ? password: xxxxxx? //授權碼,在服務選項中獲取? ? host: smtp.qq.com? //qq郵箱服務器? ? properties:? ? ? mail:? ? ? ? smtp:? ? ? ? ? ssl:enable:true//開啟安全連接
測試郵件發送
@AutowiredJavaMailSenderImpl mailSender;/*** 創建簡單消息郵件*/@Test? ? public voidtestMail(){? ? ? ? SimpleMailMessage message = new SimpleMailMessage();? ? ? ? message.setSubject("這是主題");? ? ? ? message.setText("這是內容");? ? ? ? //收件人? ? ? ? message.setTo("xxxxx@qq.com");? ? ? ? //發送人? ? ? ? message.setFrom("xxxxx@qq.com");? ? ? ? mailSender.send(message);}/**? ? * 創建復雜消息郵件? ? */? ? @Test? ? public voidtestMail02() throws MessagingException {? ? ? ? MimeMessage mimeMessage = mailSender.createMimeMessage();? ? ? ? MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);? ? ? ? helper.setSubject("這是復雜消息郵件主題");? ? ? ? helper.setText("<b style='color:red;'>這是復雜消息郵件內容</b>",true);? ? ? ? //添加附件1? ? ? ? helper.addAttachment("1.jpg",new File("E:\\desktop\\8234.jpg"));? ? ? ? //添加附件2? ? ? ? helper.addAttachment("2.docx",new File("E:\\desktop\\形勢與政策課作業.docx"));? ? ? ? //收件人? ? ? ? helper.setTo("xxxx@qq.com");? ? ? ? //發送人? ? ? ? helper.setFrom("xxxxx@qq.com");? ? ? ? mailSender.send(mimeMessage);? ? }
測試成功
在此我向大家推薦一個架構學習交流群。交流學習群號:938837867 暗號:555 里面會分享一些資深架構師錄制的視頻錄像:有Spring,MyBatis,Netty源碼分析,高并發、高性能、分布式、微服務架構的原理,JVM性能優化、分布式架構等這些成為架構師必備