spring boot异步、定时、邮件发送

异步任务

使用方法:

 

  • 在main里边加@EnableAsync 开启异步功能

@SpringBootApplication
@EnableAsync
public class SwaggerApplication {

  public static void main(String[] args) {
      SpringApplication.run(SwaggerApplication.class, args);
  }
}
  • 在方法上加@Async

邮件发送

导包

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

在配置中配置

spring.mail.username=邮箱地址
spring.mail.password=开启密码
spring.mail.host=smtp.qq.com

#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

测试

简单邮件

 @Resource
  JavaMailSenderImpl mailSender;

@Test
  void contextLoads() {
      SimpleMailMessage message = new SimpleMailMessage();
      message.setSubject("标题");
      message.setText("内容");
      message.setTo("");
      message.setFrom("");
      mailSender.send(message);
  }

带附件的邮件

 @Resource
  JavaMailSenderImpl mailSender;

  @Test
  void contextLoads() throws MessagingException {
      //一个复杂的邮件
      MimeMessage message = mailSender.createMimeMessage();
      //组装
      MimeMessageHelper helper = new MimeMessageHelper(message, true);
      message.setSubject("标题");
      message.setText("内容");
      helper.addAttachment("名字","地址");
      mailSender.send(message);
  }

定时任务

        TaskScheduler 任务调度

      TaskExecutor   任务执行
       

在main方法开启

@SpringBootApplication
@EnableScheduling
public class SwaggerApplication {

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

}

@Scheduled 什么时候执行

需要用到cron表达式

测试

@Service
public class hello {
  //秒 分 时 日 月 周几
  @Scheduled(cron = "* * * * * *")
  public void hello(){

      System.out.println("11111");
  }
}

 

猜你喜欢

转载自www.cnblogs.com/ltdh/p/12685328.html