SpringBoot中的異步任務、郵件以及定時任務

異步任務

背景

在咱們的業務處理中,好比處理完成須要3s才能完成,可是咱們須要若是要讓用戶等3s,則體驗很是差,因此咱們採用異步的方式去處理,能夠經過線程池來處理 ,可是還要寫線程,而springboot中已經默認提供了這種能力 ,咱們只要開啓便可使用。java

具體使用

  • 建立項目

咱們只要建立一個基本的springboot項目,而後只要添加web的依賴便可。web

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • 編寫場景模擬上面背景

service層:spring

@Service
public class AsyncService {

    public void sync(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("方法中在執行中");
    }

    public void async(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("方法中在執行中");
    }
}

controller層springboot

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;


    @GetMapping("/sync")
    public String sync(){
        asyncService.sync();

        return "處理完成";
    }

    @GetMapping("/async")
    public String async(){
        asyncService.async();
        
        return "處理完成";
    }

}
  • 啓動項目,測試

請求localhost:8080/sync,發現會轉圈等待3s後纔有返回值:app

image-20210110183939901

  • 問題解決

採用異步的方式來解決這個問題。異步

首先在啓動類上打開異步:@EnableAsync,而後再調用的方法上添加註解@Asyncasync

# 啓動類
 @SpringBootApplication
@EnableAsync
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
#方法
    @Async
    public void async(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("方法中在執行中");
    }

而後再次請求ocalhost:8080/async,發現咱們的方法立馬就返回了。這樣就是實現了異步任務。spring-boot

郵件任務

背景

經過springboot提供的mail-starter來實現郵件任務。單元測試

具體使用

  • 添加依賴
<!--mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • 配置文件
spring.mail.username=xxxx@qq.com
spring.mail.password=你的qq受權碼
spring.mail.host=smtp.qq.com
# qq須要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true

獲取受權碼:在QQ郵箱中的設置->帳戶->開啓pop3和smtp服務.測試

  • Spring單元測試
@Autowired
JavaMailSenderImpl mailSender;

@Test
public void contextLoads() {
   //郵件設置1:一個簡單的郵件
   SimpleMailMessage message = new SimpleMailMessage();
   message.setSubject("通知-明天來上班");
   message.setText("今晚7:30開會");

   message.setTo("xxx@qq.com");
   message.setFrom("xxx@qq.com");
   mailSender.send(message);
}

@Test
public void contextLoads2() throws MessagingException {
   //郵件設置2:一個複雜的郵件
   MimeMessage mimeMessage = mailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

   helper.setSubject("通知-明天吃飯");
   helper.setText("<b style='color:red'>今天 7:30來開會</b>",true);

   //發送附件
   helper.addAttachment("1.jpg",new File(""));
   helper.addAttachment("2.jpg",new File(""));

   helper.setTo("xxx@qq.com");
   helper.setFrom("xxx@qq.com");

   mailSender.send(mimeMessage);

定時任務

背景

在指定的時間或者場景下執行某些代碼。

相關聯的類和註解

TaskScheduler  : 任務調度者
TaskExecutor   :任務執行者
@EnableScheduling  : 開啓定時功能的註解
@schedule       :何時執行

具體使用

只要導入了springboot的web依賴,就默認給咱們導入了這個功能,不須要咱們再去導入。

關於cron表達式的能夠參考個人另外一篇文章:spring中@schedule註解的使用

  • 在啓動類上添加註解@EnableScheduling
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
  • service層編寫方法
@Service
public class ScheduleService {

    public void testSchedule(){
        System.out.println("任務被執行了");
    }
}
  • 添加註解 @Scheduled

其中的cron表達式能夠參考個人另外一篇博客:spring中@schedule註解的使用,也就是固定的時間週期去執行

@Service
public class ScheduleService {


    /**
     * 每隔10s執行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void testSchedule(){
        System.out.println(LocalDateTime.now()+"任務被執行了");
    }
}
  • 結果

每隔10s執行一次,驗證了準確性。

image-20210111212812666

相關文章
相關標籤/搜索