SpringBoot任務篇Ⅴ --- 異步任務、定時任務、郵件任務

Java的任務在項目中須要用到的地方不少,好比,每個月月末的財務報表給財務部門,定時給領導發個郵件短信等等。這時候咱們就須要用到任務了,任務調度自己涉及到多線程併發、運行時間規則制定和解析、場景保持與恢復、線程池維護等諸多方面的工做。以前的學習中也使用過任務的框架Quartz,用起來也十分地編輯。本篇文章主要講的是SpringBoot中基於註解的任務調度的簡單使用。html

 一.異步任務spring

正常狀況下,同一線程中的方法是同步執行的,好比我要請求一段數據,可是這個數據等待service層執行3s以後,而後才能返回給我,並且這個service層與我想到獲得的數據沒有絲毫關係。若是想要不等待service層處理數據的話,只能開啓一個線程去執行service層方法,而後另一個線程直接返回數據給我。可是這樣作的話會變得很麻煩,因此咱們可使用異步任務的方式,就能夠實現我上面的需求。安全

1.1 開啓異步任務註解服務器

@SpringBootApplication
@EnableAsync //開啓異步註解
public class Springboot04TaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot04TaskApplication.class, args);
    }

}

1.2 異步任務執行方法多線程

@Service
public class AsyncService {
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("處理數據中");
    }
}

1.3 異步任務測試併發

@Controller
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        asyncService.hello();
        return "success";
    }
}

運行項目,訪問「/hello」請求,若頁面沒有通過等待直接返回「success」數據,通過3s以後控制檯打印了「處理數據中」說明該異步任務執行成功。app

 

二.定時任務框架

定時任務的使用方式和異步任務的差很少。不過須要注意的是定時任務的core表達式。異步

2.1 core表達式jvm

例如:

@Scheduled(cron = "0 * * * * MON-SAT")  每分鐘的整秒的時候執行該方法

@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")  每分鐘0,1,3,4秒的的時候執行該方法

@Scheduled(cron = "0-4 * * * * MON-SAT")  每分鐘0,1,3,4秒的的時候執行該方法

@Scheduled(cron = "0/4 * * * * MON-SAT") 每四秒執行一次 (/設定步長)

@Scheduled(cron = "0 0 2-4 ? * 1#1") 每月的第一個週一凌晨2點到4點期間, 每一個整點都執行一次

2.2 定時任務使用

@EnableScheduling //開啓定時任務註解
@SpringBootApplication
public class Springboot04TaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot04TaskApplication.class, args);
    }

}
@Service
public class ScheduledService {
    /**
     * second,minute,hour,day of month,month,day of week
     * 0 * * * * MON-FRI
     */
    @Scheduled(cron = "0/4 * * * * MON-SAT")  //每四秒執行一次 (/設定步長)
    public void say(){
        System.out.println("Hello...");
    }
}

 

三.郵件任務

SpringBoot還整合了郵件任務功能,這使得郵箱服務器發送郵件變得十分容易。

3.1 準備工做

3.1.1 導入郵件任務依賴

 <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-mail</artifactId>
         <scope>test</scope>
 </dependency>

3.1.2 郵箱配置

準備兩個郵箱,一個用來發送郵件,另外一個用來接收郵件。其中發件的郵箱須要配置開啓一下SMTP服務器服務,開啓的後會獲得發件郵箱密鑰,記得保存起來,這將會在後面用到。

3.2 配置參數

spring.mail.username=**********@qq.com
#填入上面開啓服務得到的密鑰
spring.mail.password=*************
spring.mail.host=smtp.qq.com
#配置安全連接
spring.mail.properties.mail.smtp.ssl.enable=true

3.3 發送簡單郵件

@Autowired
JavaMailSenderImpl mailSender;
@Test
    public void contextLoads() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("通知");//設置標題
        simpleMailMessage.setText("恭喜你得到了優秀員工獎");//內容
        simpleMailMessage.setTo("*********@163.com"); //收件人郵箱帳戶
        simpleMailMessage.setFrom("********@qq.com"); //寄件人郵箱帳戶
        mailSender.send(simpleMailMessage);
    }

3.4 發送複雜郵件

@Autowired
JavaMailSenderImpl mailSender;
@Test
    public void compMail(){
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setSubject("重要通知");//設置標題
            mimeMessageHelper.setText("恭喜你得到了優秀員工獎");//內容
            mimeMessageHelper.setText("<b style='color:red'>年終獎翻倍</b>",true);//內容  第二個參數設置是否識別html,true表示識別爲html內容
            mimeMessageHelper.addAttachment("1.jpg",new File("C:\\Users\\admin\\Desktop\\快遞\\快遞面單\\圓通.png")); //傳輸文件
            mimeMessageHelper.addAttachment("2.jpg",new File("C:\\Users\\admin\\Desktop\\workdown\\pic\\jvm運行時數據區域.jpg"));
            mimeMessageHelper.setTo("************@163.com"); //收件人郵箱
            mimeMessageHelper.setFrom("*********@qq.com"); //寄件人郵箱
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
相關文章
相關標籤/搜索