1. 程式人生 > >SpringBoot中的非同步任務、定時任務和郵件任務

SpringBoot中的非同步任務、定時任務和郵件任務

一、SpringBoot中的非同步任務

在Java應用中,絕大多數情況下都是通過同步的方式來實現互動處理的,但是在處理與第三方系統互動的時候,容易造成響應遲緩的情況,之前大部分都是使用多執行緒來完成此類任務,其實,在Spring 3.x之後,就已經內建了@Async來完美解決這個問題。

1、模擬長時間服務呼叫
//Service類
@Service
public class AsyncService {
   
    public void hello(){

        try {
        	//讓執行緒休眠3秒,模擬長時間無響應
            Thread.
sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("業務正在處理中……"); } }
//Controller類
@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello
(){ //呼叫Service類 asyncService.hello(); return "success"; } }
//啟動類
@SpringBootApplication
public class SpringbootTaskApplication {

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

}
2、執行結果:(輸入請求地址後,會等待3秒,才會有輸出)

在這裡插入圖片描述

3、採用非同步方式:

用@Async 註解,修飾Service中需要執行非同步的方法

@Service
public class AsyncService {

    @Async //該方法是非同步的
    public void hello(){

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("業務正在處理中……");

    }
}
@EnableAsync //開啟非同步註解功能
@SpringBootApplication
public class SpringbootTaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTaskApplication.class, args);
    }
}
4、測試結果:開啟瀏覽器,重新發送請求,頁面及時響應,無須等待3秒
5、小節

兩個註解:
@Aysnc:該註解修飾需要執行非同步的方法;
@EnableAysnc:該註解是開啟非同步註解的功能;別忘記開啟

二、SpringBoot中的定時任務

專案開發中經常需要執行一些定時任務,比如需要在每天凌晨時候,分析一次前一天的日誌資訊。Spring為我們提供了非同步執行任務排程的方式。

1、需要定時執行的Service服務
@Service
public class ScheduledService {
	//定時執行表示式
    @Scheduled(cron = "0 * * * * MON-SAT")
    public void hello(){

        System.out.println("hello……");

    }
}

需要開啟@EnableScheduling 註解

@EnableScheduling //開啟定時任務功能
@SpringBootApplication
public class SpringbootTaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTaskApplication.class, args);
    }
}
3、測試結果:(每分鐘的0秒,列印hello……)

在這裡插入圖片描述

4、cron 表示式

在這裡插入圖片描述

在這裡插入圖片描述

5、小節

兩個註解:
@EnableScheduling:開啟定時任務註解
@Scheduled:標註方法執行定時任務

三、SpringBoot中的郵件任務

1、新增mail依賴:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、編寫測試程式碼:
RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootTaskApplicationTests {

    @Autowired
    JavaMailSenderImpl javaMailSender;


    @Test
    public void contextLoads() {
		//普通的文字郵件
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

        simpleMailMessage.setSubject("放假通知");
        simpleMailMessage.setText("下週放假");
        simpleMailMessage.setTo("*******.com");
        simpleMailMessage.setFrom("[email protected]");

        javaMailSender.send(simpleMailMessage);

    }

    @Test
    public void test02() throws MessagingException {
		//帶附件的的郵件
        MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMailMessage,true);

        helper.setSubject("通知-放假通知");
        helper.setText("<b style='color:red'>下週放假</b>",true);
        helper.setTo("**********.com");
        helper.setFrom("[email protected]");

        helper.addAttachment("1.jpg",new File("C:\\Users\\Think\\Downloads\\scorpios.group_cert.jpg"));
        helper.addAttachment("2.jpg",new File("C:\\Users\\Think\\Downloads\\scorpios.xin_cert.jpg"));

        javaMailSender.send(mimeMailMessage);

    }
 }
3、配置檔案
//傳送者的郵件
[email protected]
//不是郵箱的密碼,是授權碼
spring.mail.password=XXXXXXXX(檢視自己的授權碼)
spring.mail.host=smtp.qq.com
4、配置QQ郵箱,獲取授權碼

第一步:
在這裡插入圖片描述
第二步:
在這裡插入圖片描述
第三步:
在這裡插入圖片描述
第四步:
在這裡插入圖片描述

5、測試結果

在這裡插入圖片描述
在這裡插入圖片描述

四、小結

SpringBoot提供了非同步任務、定時任務、郵件任務的功能。
非同步任務:

@Aysnc:該註解修飾需要執行非同步的方法;
@EnableAysnc:該註解是開啟非同步註解的功能;

定時任務:

@EnableScheduling:開啟定時任務註解
@Scheduled:標註方法執行定時任務

郵件任務:

引入依賴
配置郵件賬號
使用JavaMailSenderImpl 傳送郵件