springboot的WEB开发笔记(异步,邮箱,定时任务)

异步,邮箱,定时任务

  • 任务
    • 异步任务
    • 邮箱任务
    • 定时任务

任务

异步任务

应用类添加@EnableAsync开启异步注解功能

@EnableAsync//开启异步注解功能
@SpringBootApplication
public class AsynchronousApplication {

    public static void main(String[] args) {
        SpringApplication.run(AsynchronousApplication.class, args);
    }

}

并在需要异步处理的类上添加@Async即可,效果是边返回页面结果,后台边处理任务

@Service
@Async//异步处理的注解
public class AsynService {
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("加载中");
    }
}

邮箱任务

①导入依赖

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

②编写配置

spring:
  mail:
    username: [email protected]
    password: daobrayydixrbbfg
    host: smtp.qq.com
    properties:
      mail:
        smtl:
          ssl:
            enable: true

③编写测试

@Autowired
private JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    simpleMailMessage.setSubject("你好");
    simpleMailMessage.setText("我好");
    simpleMailMessage.setTo("[email protected]");
    simpleMailMessage.setFrom("[email protected]");
    mailSender.send(simpleMailMessage);
}

将复杂的邮箱发送进行封装

public static class My_File{
        private String name;
        private String path;
    }
    /**
     *封装复杂性发送邮箱
     * @param html:是否为html格式
     * @param subject:标题
     * @param text:文本
     * @param from:发件邮箱
     * @param to:收件邮箱
     * @param fileList:附件文件
     * @throws MessagingException
     */
    public void sendEmail(Boolean html, String subject, String text, String from, String to, List<My_File> fileList) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper =new MimeMessageHelper(mimeMessage,html);
        //标题和正文
        helper.setSubject(subject);
        helper.setText(text,html);
        //附件
        for(My_File file:fileList){
            helper.addAttachment(file.name,new File(file.path));
        }

        helper.setTo(to);
        helper.setFrom(from);
        mailSender.send(mimeMessage);
    }

定时任务

在应用类添加注解@EnableScheduling

在需要定时执行的方法上添加 @Scheduled(),用cron表达式去表达时间点,cron换算网址:https://cron.qqe2.com/

@Service
public class ScheduleService {
    /**
     * cron:秒 分 时 日 月 星期
     */
    @Scheduled(cron = "0 49 15 * * ?")
    public void hello(){
        System.out.println("执行");
    }
}

你可能感兴趣的:(spring,boot)