異步任務
-
創建一個Hello項目
-
創建一個類AsyncService
異步處理還是非常常用的,比如我們在網站上發送郵件,后臺會去發送郵件,此時前臺會造成響應不動,直到郵件發送完畢,響應才會成功,所以我們一般會采用多線程的方式去處理這些任務。
編寫方法,假裝正在處理數據,使用線程設置一些延時,模擬同步等待的情況;
@Service public class AsyncService {public void hello(){try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("業務進行中....");} }
-
編寫AsyncController類
我們去寫一個Controller測試一下
@RestController public class AsyncController {@Autowiredprivate AsyncService asyncService;@GetMapping("/hello")public String hello(){asyncService.hello();return "OK";}}
-
訪問http://localhost:8080/hello進行測試,3秒后出現OK,這是同步等待的情況。
問題:我們如果想讓用戶直接得到消息,就在后臺使用多線程的方式進行處理即可,但是每次都需要自己手動去編寫多線程的實現的話,太麻煩了,我們只需要用一個簡單的辦法,在我們的方法上加一個簡單的注解即可,如下:
-
給hello方法添加
@Async
注解;//告訴Spring這是一個異步方法 @Async public void hello(){try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("業務進行中...."); }
SpringBoot就會自己開一個線程池,進行調用!但是要讓這個注解生效,我們還需要在主程序上添加一個注解
@EnableAsync
,開啟異步注解功能;@EnableAsync //開啟異步注解功能 @SpringBootApplication public class SpringbootTaskApplication {public static void main(String[] args) {SpringApplication.run(SpringbootTaskApplication.class, args);}}
7、重啟測試,網頁瞬間響應,后臺代碼依舊執行!
郵件任務
郵件發送,在我們的日常開發中,也非常的多,Springboot也幫我們做了支持
- 郵件發送需要引入
spring-boot-start-mail
- SpringBoot 自動配置
MailSenderAutoConfiguration
- 定義
MailProperties
內容,配置在application.yml
中 - 自動裝配
JavaMailSender
- 測試郵件發送
測試:
-
引入pom依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId> </dependency>
看它引入的依賴,可以看到 jakarta.mail
<dependency><groupId>com.sun.mail</groupId><artifactId>jakarta.mail</artifactId><scope>compile</scope> </dependency>
-
查看自動配置類:MailSenderAutoConfiguration
這個類中存在bean,
JavaMailSenderImpl
然后我們去看下配置文件
@ConfigurationProperties(prefix = "spring.mail") public class MailProperties {private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;private String host;private Integer port;private String username;private String password;private String protocol = "smtp";private Charset defaultEncoding = DEFAULT_CHARSET;private Map<String, String> properties = new HashMap<>();private String jndiName;//set、get方法省略。。。 }
-
配置文件:
spring:mail:username: 2356731504@qq.compassword: 你的qq授權碼host: smtp.qq.comproperties:mail:smtp:ssl:enable: true # qq需要配置ssl
獲取授權碼:在QQ郵箱中的設置->賬戶->開啟pop3和smtp服務
-
Spring單元測試
package com.liming;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSenderImpl;import org.springframework.mail.javamail.MimeMessageHelper;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import java.io.File;@SpringBootTestclass HelloApplicationTests {@Autowiredprivate JavaMailSenderImpl javaMailSender;//郵件設置1:一個簡單的郵件@Testvoid contextLoads() {SimpleMailMessage mailMessage = new SimpleMailMessage();mailMessage.setSubject("黎明,你好"); // 主題mailMessage.setText("這是郵件發送測試。。。"); // 正文mailMessage.setTo("2356731504@qq.com"); // 發送給誰mailMessage.setFrom("2356731504@qq.com"); // 誰發javaMailSender.send(mailMessage);}// 一個復雜的郵件@Testvoid contextLoads2() throws MessagingException {MimeMessage mimeMessage = javaMailSender.createMimeMessage();//組裝MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);//正文helper.setSubject("黎明,你好~plus");helper.setText("<p style='color:red'>這是郵件發送測試</p>", true);//附件helper.addAttachment("1.jpg", new File("D:\\Users\\Pictures\\Saved Pictures\\SAP-ABAP.jpg"));helper.addAttachment("2.jpg", new File("D:\\Users\\Pictures\\Saved Pictures\\SAP-ABAP.jpg"));helper.setTo("2356731504@qq.com");helper.setFrom("2356731504@qq.com");javaMailSender.send(mimeMessage);}}