SpringBoot【四】 任务

任务

异步任务

  1. 在 service 包下建一个 AsyncService 类,编写一个方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况

    @Service
    public class AsyncService {
    
        public void hello(){
            try {
                Thread.sleep(3000); //模拟延迟
            } catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("数据正在处理。。。");
        }
    }
    
  2. 在 controller 包下建一个 AsyncController 类

    @RestController
    public class AsyncController {
    
        @Autowired
        AsyncService asyncService;
    
        @RequestMapping("/hello")
        public String hello(){
            asyncService.hello();
            return "OK";
        }
    }
    
  3. 测试,访问 http://localhost:8080/hello ,3 秒之后才出现 OK,这是同步等待的情况

    问题:如果想让用户直接得到消息,就在后台使用多线程的方式进行处理即可,但是每次都需要自己手动去编写多线程的实现的话太麻烦,我们只需要用一个简单的办法,在方法上加一个简单的注解即可

  4. 给 hello 方法添加 @Async 注解

    // 告诉Spring这是一个异步方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000); //模拟延迟
        } catch (InterruptedException e){
            e.printStackTrace();
        }
        System.out.println("数据正在处理。。。");
    }
    
  5. SpringBoot 会自己开一个线程池,进行调用,但是要让这个注解生效,还需要在主程序上添加一个注解@EnableAsync,开启异步注解功能

    // 开启异步注解功能
    @EnableAsync
    @SpringBootApplication
    public class Springboot09TestApplication {
       public static void main(String[] args) {
          SpringApplication.run(Springboot09TestApplication.class, args);
       }
    }
    
  6. 重启测试,网页瞬间响应,后台代码依旧会有 3 秒的处理时间。

定时任务

  • 接口:

    • TaskExecutor 任务执行者
    • TaskScheduler 任务调度者
  • 注解:

    • @EnableScheduling // 开启定时功能的注解
    • @Scheduled //什么时候执行
  • corn 表达式

  1. 创建一个 ScheduledService 类,编写一个方法,这个方法需要定时执行

    @Service
    public class ScheduledService {
    
        // 让这个方法在一个特定的时间执行
        // cron 表达式
        // 秒 分 时 日 月 周几
        /*
            "30 10 18 * * ?"  每天的 18点10分30秒 执行一次
            "30 0/5 10,18 * * ?"  每天的 10点和18点,每隔5分钟 执行一次
         */
        @Scheduled(cron = "0 10 18 * * ?")
        public void hello(){
            System.out.println("hello,你被执行了");
        }
    }
    
  2. 编写完定时任务之后,需要在主程序上增加 @EnableScheduling 开启定时任务功能

    @EnableAsync // 开启异步注解功能
    @EnableScheduling // 开启定时功能的注解
    @SpringBootApplication
    public class Springboot09TestApplication {
       public static void main(String[] args) {
          SpringApplication.run(Springboot09TestApplication.class, args);
       }
    }
    

邮件发送

  • 邮件发送需要引入spring-boot-start-mail
  • SpringBoot 自动配置MailSenderAutoConfiguration
  • 定义MailProperties内容,配置在application.yml中
  • 自动装配JavaMailSender
  • 测试邮件发送
  1. 导入依赖

    <!--javax.mail:配置-->
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    
  2. 查看自动配置类:MailSenderAutoConfiguration,这个类中存在 bean,JavaMailSenderImpl

    配置信息类为 MailProperity

    @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;
        ...
    }
    
  3. 自定义配置 application.properties

    spring.mail.username=1064971297@qq.com
    # 邮件授权码 gvrpmlapouwjbeci
    spring.mail.password=gvrpmlapouwjbeci
    spring.mail.host=smtp.qq.com
    # 开启加密验证,qq邮箱需要开启
    spring.mail.properties.mail.smtp.ssl.enable=true
    

    注意:password 中为邮件授权码,通过【QQ邮箱中的设置->账户->开启pop3和smtp服务】获取

  4. Spring 单元测试

    @Autowired
    JavaMailSenderImpl mailSender;
    
    @Test
    void contextLoads() {
       //一个简单的邮件
       SimpleMailMessage mailMessage = new SimpleMailMessage();
    
       mailMessage.setSubject("这是主题");
       mailMessage.setText("这是内容");
       mailMessage.setTo("1064971297@qq.com");
       mailMessage.setFrom("1064971297@qq.com");
    
       mailSender.send(mailMessage);
    }
    
    @Test
    void contextLoads2() throws MessagingException {
        //一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("主题");
        helper.setText("<p style='color:red'>内容</p>", true); //true开启html支持
        // 附件
        helper.addAttachment("1.jpg", new File("C:\Users\Administrator\Desktop\1.jpg"));
        helper.addAttachment("2.jpg", new File("C:\Users\Administrator\Desktop\1.jpg"));
    
        helper.setTo("1064971297@qq.com");
        helper.setFrom("1064971297@qq.com");
    
        mailSender.send(mimeMessage);
    }
    
  5. 运行,查看邮箱,邮件接收成功。

抽取一个邮件发送的方法:

/**
 * @param html
 * @param subject
 * @param text
 * @param thtml
 * @param filename
 * @param file
 * @param to
 * @param from
 * @throws MessagingException
 * @Author Songzw
 */
public void sendMail(Boolean html, String subject, String text, boolean thtml, String filename, File file, String to, String from) throws MessagingException {
   //一个复杂的邮件
   MimeMessage mimeMessage = mailSender.createMimeMessage();
   //组装
   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, html);
   helper.setSubject(subject);
   helper.setText(text, thtml); //true开启html支持
   // 附件
   helper.addAttachment(filename, file);

   helper.setTo(to);
   helper.setFrom(from);

   mailSender.send(mimeMessage);
}
原文地址:https://www.cnblogs.com/Songzw/p/13285070.html