天天看點

SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務

系列文章

SpringBoot 01 —— HelloSpringBoot、yaml配置、資料校驗、多環境切換

SpringBoot 02 —— Web簡單探究、員工管理系統

SpringBoot 03 —— Spring Security

SpringBoot 04 —— Shiro

SpringBoot 05 —— Swagger

SpringBoot 06 —— 異步任務、郵件任務、定時任務

SpringBoot 07 —— 分布式:Dubbo+Zookeeper

文章目錄

  • 系列文章
  • 1、異步任務
  • 2、郵件任務
  • 3、定時任務

1、異步任務

當我們在網頁中發起某個請求,而請求處理需要耗費一定時間時,我們常常會用異步任務來完成。這其實類似于多線程處理,我們會先給使用者一個回報,然後在背景進行處理。

未使用異步任務

1、service/AysnService.java

@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @RequestMapping("/request")
    public String request(){
        asyncService.hello();//會睡眠三秒,頁面持續轉圈。
        return "處理完畢!";
    }
}
           

2、controller/AsyncController.java

@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @RequestMapping("/request")
    public String request(){
        asyncService.hello();//會睡眠三秒,頁面持續轉圈。
        return "處理完畢!";
    }
}
           

3、啟動後,要3秒才能得到結果。

SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務
SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務
SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務

使用異步任務

會開啟一個線程池,用另一個線程執行異步方法。

1、在啟動程式開啟異步

@EnableAsync //開啟異步
@SpringBootApplication
public class Springboot09TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }

}
           

2、把方法改為異步方法

@Service
public class AsyncService {
    @Async//異步方法
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("資料正在處理");
    }
}
           

3、再次運作後,立即得到回報,背景會繼續處理資料。

SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務
SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務

2、郵件任務

1、導入郵件啟動器

<!-- 裡面就導入了javax.mail  -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
           

2、開啟郵箱POP3/SMTP服務

SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務

開啟後,會得到一個密碼

SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務

3、application.properties配置郵件服務

# 發送方郵箱
[email protected]
# POP3/SMTP服務 伺服器郵箱的密碼
spring.mail.password=這裡填自己擷取到的密碼
# 郵件主機 QQ郵箱
spring.mail.host=smtp.qq.com
# QQ郵箱 需要開啟加密驗證(這裡其實是一個Map鍵值對 "mail.smtp.ssl.enable":"true"
spring.mail.properties.mail.smtp.ssl.enable=true
           

4、程式設計(兩個方法可寫在Controller裡面,這裡是為了友善測試)

@SpringBootTest
class Springboot09TestApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void simpleMail() {
        //發送簡單郵件
        SimpleMailMessage mailMessage = new SimpleMailMessage();

        mailMessage.setSubject("同學,你好~");//主題
        mailMessage.setText("Java 路上持續學習!!");//内容
        mailMessage.setTo("[email protected]");//發給誰(可寫多個)
        mailMessage.setFrom("[email protected]");//由誰發出

        mailSender.send(mailMessage);
    }

    @Test
    void mimeMail() throws MessagingException {
        //發送複雜郵件
        MimeMessage mimeMessage = mailSender.createMimeMessage();//加參數可從檔案流讀取
        // true 支援多檔案上傳
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setSubject("同學,你好~plus版");//主題
        //支援解析HTML格式的内容
        messageHelper.setText("<h1> Java 路上持續學習!!plus版 </h1>", true);
        //附件(檔案名、File對象)
        messageHelper.addAttachment("1.png", new File("C:\\Users\\11427\\Desktop\\qq.png"));
        messageHelper.addAttachment("2.png", new File("C:\\Users\\11427\\Desktop\\qq.png"));
        messageHelper.setTo("[email protected]");//發給誰
        messageHelper.setFrom("[email protected]");//由誰發

        mailSender.send(mimeMessage);
    }

}
           

效果:

  1. 簡單郵件
    SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務
  2. 複雜郵件
SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務

3、定時任務

顧名思義,在指定時間執行方法。

1、開啟定時功能

@EnableAsync//打開異步功能
@EnableScheduling//打開定時功能
@SpringBootApplication
public class Springboot09TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }

}
           

2、編寫定時方法

@Service
public class ScheduledService {
    /**在一個特定的事件執行這個方法(有點像Timer)
     * 這裡會用到cron表達式,具體方法可百度,一般情況下要什麼時間都可直接去網上找
     * https://cron.qqe2.com/ 可查詢具體怎麼寫
     * 這裡簡單說明:秒 分 時 日 月 周幾
     */
    @Scheduled(cron = "* * * * * ?")//每秒執行一次
    public void hello(){
        System.out.println("執行了一次方法!");
    }
}
           
SpringBoot 06 —— 異步任務、郵件任務、定時任務系列文章1、異步任務2、郵件任務3、定時任務

繼續閱讀