8、Spring Boot任务

1.异步任务

  Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。

  主要使用两个注解完成,@EnableAysnc、@Aysnc

(1).Springboot04TaskApplication.java

@EnableAsync    //开启异步注解功能

@SpringBootApplication

public class Springboot04TaskApplication {

 

   public static void main(String[] args) {

      SpringApplication.run(Springboot04TaskApplication.class, args);

   }

 

}

(2).AsyncController.java

package com.hosystem.task.controller;

 

import com.hosystem.task.service.AsyncService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

public class AsyncController {

 

    @Autowired

    AsyncService asyncService;

 

    @GetMapping(“/hello”)

    public String hello(){

        asyncService.hello();

        return “success”;

    }

}

(3).AsyncService.java

package com.hosystem.task.service;

 

import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Service;

 

@Service

public class AsyncService {

 

    //通知spring这是一个异步方法

    @Async

    public void hello(){

        try {

            Thread.sleep(3000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println(处理数据….”);

    }

}

 

2.定时任务

  开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor 、TaskScheduler 接口。

  使用到的注解有两个,@EnableScheduling、@Scheduled

  Cron表达式:

 

(1).ScheduledService.java

package com.hosystem.task.service;

 

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Service;

 

@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 * * * * 0-7”)  //4秒执行一次

    public void hello() {

        System.out.println(“hello …”);

    }

}

(2).Springboot04TaskApplication.java

package com.hosystem.task;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.scheduling.annotation.EnableAsync;

import org.springframework.scheduling.annotation.EnableScheduling;

import org.springframework.scheduling.annotation.Scheduled;

 

@EnableScheduling //开启基于注解定时任务

@SpringBootApplication

public class Springboot04TaskApplication {

 

   public static void main(String[] args) {

      SpringApplication.run(Springboot04TaskApplication.class, args);

   }

 

}

3.邮件任务

 

 

(1).导入pom.xml

<!–mail–>

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-mail</artifactId>

</dependency>

(2).开启POP3/SMTP

 

(3).开启IMAP/SMTP

 

(4).生成授权码

 

(5).applicaiton.properties

server.port=80

 

#配置邮箱信息

spring.mail.username=[email protected]

#授权码

spring.mail.password=password

#smtp地址

spring.mail.host=smtp.qq.com

spring.mail.protocol=smtp

spring.mail.properties.mail.smtp.ssl.enable=true

(6).Springboot04TaskApplicationTests.java

  SendMailTest测试邮箱发送,一定要在mail中开启SMTP

package com.hosystem.task;

 

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.internet.MimeMessage;

import java.io.File;

 

@SpringBootTest

class Springboot04TaskApplicationTests {

 

   @Autowired

   JavaMailSenderImpl mailSender;

 

   @Test

   public void contextLoads() {

      SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

      //邮件设置

      simpleMailMessage.setSubject(通知—–“);

      simpleMailMessage.setText(学习java”);

  //setTo:目的邮件地址  setFrom:发送邮件地址

      simpleMailMessage.setTo([email protected]);

      simpleMailMessage.setFrom(username@qq.com”);

      mailSender.send(simpleMailMessage);

   }

 

   @Test

   public void test01() throws Exception{

      //1.创建一个复杂的消息邮件

      MimeMessage mimeMessage = mailSender.createMimeMessage();

      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

 

      //邮件设置

      helper.setSubject(通知—–“);

 

      /**

       *     public void setText(String text) throws MessagingException {this.setText(text, false);

       }

       */

      helper.setText(“<b style=’color:red’>学习java</b>”,true);

  //setTo:目的邮件地址  setFrom:发送邮件地址

      helper.setTo(username@163.com”);

      helper.setFrom(username@qq.com”);

 

      //上传文件

      helper.addAttachment(“8a92681cb892bf78ec83af62f2b6a82.jpg”,new File(“E:\\Users\\Asuna\\Desktop\\html\\8a92681cb892bf78ec83af62f2b6a82.jpg”));

      helper.addAttachment(“8f82df421233241732db6ec6baed07e.jpg”,new File(“E:\\Users\\Asuna\\Desktop\\html\\8f82df421233241732db6ec6baed07e.jpg”));

 

 

      mailSender.send(mimeMessage);

   }

 

}

  

参考文档:

//github.com/spring-projects/spring-boot/tree/v2.1.0.RELEASE/spring-boot-project/spring-boot-starters