Spring Boot與任務

異步任務、定時任務、郵件任務

1、異步任務
在Java應用中,絕大多數狀況下都是經過同步的方式來實現交互處理的;可是在處理與第三方系統交互的時候,容易形成響應遲緩的狀況,以前大部分都是使用多線程來完成此類任務,其實,在Spring 3.x以後,就已經內置了@Async來完美解決這個問題。java

**兩個註解:
@EnableAysnc、@Aysnc**
2、定時任務
項目開發中常常須要執行一些定時任務,好比須要在天天凌晨時候,分析一次前一天的日誌信息。Spring爲咱們提供了異步執行任務調度的方式,提供TaskExecutor 、TaskScheduler 接口。
**兩個註解:@EnableScheduling、@Scheduled
cron表達式:**
image.pngspring

@Service
public class ScheduledService {

    /**
     * second(秒), minute(分), hour(時), day of month(日), month(月), day of week(周幾).
     * 0 * * * * MON-FRI
     *  【0 0/5 14,18 * * ?】 天天14點整,和18點整,每隔5分鐘執行一次
     *  【0 15 10 ? * 1-6】 每月的週一至週六10:15分執行一次
     *  【0 0 2 ? * 6L】每月的最後一個週六凌晨2點執行一次
     *  【0 0 2 LW * ?】每月的最後一個工做日凌晨2點執行一次
     *  【0 0 2-4 ? * 1#1】每月的第一個週一凌晨2點到4點期間,每一個整點都執行一次;
     */
   // @Scheduled(cron = "0 * * * * MON-SAT")
    //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
   // @Scheduled(cron = "0-4 * * * * MON-SAT")
    @Scheduled(cron = "0/4 * * * * MON-SAT")  //每4秒執行一次
    public void hello(){
        System.out.println("hello ... ");
    }
}

3、郵件任務多線程

  1. 郵件發送須要引入spring-boot-starter-mail
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  1. Spring Boot 自動配置MailSenderAutoConfiguration
@EnableAsync  //開啓異步註解功能
@EnableScheduling //開啓基於註解的定時任務
@SpringBootApplication
public class Springboot04TaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot04TaskApplication.class, args);
    }
}
  1. 定義MailProperties內容,配置在application.yml中
spring.mail.username=534096094@qq.com
spring.mail.password=gtstkoszjelabijb
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
  1. 自動裝配JavaMailSender
  2. 測試郵件發送

image.png

@Autowired
    JavaMailSenderImpl mailSender;

    @Test
    public void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();
        //郵件設置
        message.setSubject("通知-今晚開會");
        message.setText("今晚7:30開會");

        message.setTo("17512080612@163.com");
        message.setFrom("534096094@qq.com");

        mailSender.send(message);
    }

    @Test
    public void test02() throws  Exception{
        //一、建立一個複雜的消息郵件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        //郵件設置
        helper.setSubject("通知-今晚開會");
        helper.setText("<b style='color:red'>今天 7:30 開會</b>",true);

        helper.setTo("17512080612@163.com");
        helper.setFrom("534096094@qq.com");

        //上傳文件
        helper.addAttachment("1.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\1.jpg"));
        helper.addAttachment("2.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\2.jpg"));

        mailSender.send(mimeMessage);

    }

注意:
在進行測試的時候,須要獲取其驗證
image.pngapp

image.png
順便說一下個人我的博客
天涯博客
謝謝!!!異步

相關文章
相關標籤/搜索