一、异步任务
1.在主启动类中开启 开启异步注解功
@EnableAsync
2.编写一个 service层 编一些方法,在方法上添加注解 @Async
@Async
public void hello(){
try{
Thread.sleep(3000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
3.在 controller层 调用 service层 的方法
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "ok";
}
}
4.效果
访问页面的时候展示ok,3秒后在控制台打印 " 数据正在处理… "
二、邮件任务
1.处理邮件任务,首先要导入相关依赖
<!-- javax.mail start-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- javax.mail end-->
2.在 application.properties 中配置邮件账户信息
- spring.mail.password,需要在邮箱设置中开启 POP3/SMTP服务 然后获取
- 使用qq邮箱时,需要开启加密验证
spring.mail.properties.mail.smtl.ssl.enbale=true
spring: #配置邮件 mail: username: jan991214@163.com password: DLLXPTQNWORWUVHB host: smtp.163.com port: 25 properties: mail: debug: true smtp: #设置邮件发送超时时间
3.编写发送邮件的方法
- 为了方便测试,在test中编写
-
简单邮件TEST:
@Autowired JavaMailSenderImpl mailSender; @Test void contextLoads() { //查看一下默认的数据源 System.out.println(dataSource.getClass()); //一个简单的邮件发送 SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setSubject("TEST"); mailMessage.setText("Springboot邮件测试"); mailMessage.setTo("jan991214@163.com"); mailMessage.setFrom("jan991214@163.com"); try{ mailSender.send(mailMessage); }catch(Exception e){ System.out.println("--------"+e+"--------"); } }
复杂邮件TEST:
@Autowired JavaMailSenderImpl mailSender; @Test void contextLoads2() throws MessagingException { //一个复杂的邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); //组装 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true); //正文 try{ helper.setSubject("Test"); helper.setText("<p style='color:red'>Springboot的复杂邮件TEST!</p>",true); //附件 helper.addAttachment("1.jpg",new File("C:\\Users\\Vulcan\\Desktop\\1.jpg")); helper.addAttachment("2.jpg",new File("C:\\Users\\Vulcan\\Desktop\\1.jpg")); helper.setTo("jan991214@163.com"); helper.setFrom("jan991214@163.com"); mailSender.send(mimeMessage); }catch(Exception e){ System.out.println("------"+e+"-------"); } }
三、定时任务
1.在主启动类开启定时任务注解 @EnableScheduling
2.cron表达式(百度有在线生产器)
3.在方法上加注解 @Scheduled(cron表达式)
代码中注释讲解了部分表达式
@Service
public class ScheduledService {
// 在一个特定时间执行这个方法
// cron 表达式
// 秒 分 时 日 月 周几~
/*
* 0 45 14 * * ? 每天的14点45分执行
* 0 0/5 10,18 * * ? 每天的10点和18点,每隔5分钟执行一次
* */
@Scheduled(cron = "0 45 14 * * ?")
public void hello(){
System.out.println("你被执行了");
}
}
转载自:【SpringBoot】处理异步、邮件、定时任务(解决了阿里云服务器 Mail server connection failed 异常)_Lzy_First的博客-CSDN博客