一、异步任务
- 在主启动类中开启 开启异步注解功能
@EnableAsync
- 编写一个 service层 编一些方法,在方法上添加注解 @Async
@Async
public void hello(){
try{
Thread.sleep(3000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
- 在 controller层 调用 service层 的方法
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "ok";
}
}
- 效果
- 访问页面的时候展示ok,3秒后在控制台打印 " 数据正在处理… "
二、邮件任务
- 处理邮件任务,首先要导入相关依赖
<!--javax.mail-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- 在 application.properties 中配置邮件账户信息
- spring.mail.password,需要在邮箱设置中开启 POP3/SMTP服务 然后获取
- 使用qq邮箱时,需要开启加密验证
spring.mail.properties.mail.smtl.ssl.enbale=true
spring.mail.username=11111111@qq.com
# password 开启POP3/SMTP服务时返回的密码
spring.mail.password=aaaaaaaaaaa
spring.mail.host=smtp.qq.com
# 开启加密验证,qq邮件需要
spring.mail.properties.mail.smtl.ssl.enbale=true
- 编写发送邮件的方法
- 为了方便测试,在test中编写
@SpringBootTest
class TaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("你好,我在用springboot测试邮件任务发送");
mailMessage.setText("谢谢你的配合,mua!");
mailMessage.setTo("111@qq.com"); // 目标邮箱地址
mailMessage.setFrom("222@qq.com");
mailSender.send(mailMessage);
}
}
- 部署到阿里云ECS服务器上出现 Mail server connection failed 异常的处理方法
在本地测试的时候,没有问题,但是部署到服务器上就出现异常原因如下:
- 本地服务器使用的是25端口进行邮件发送,但是阿里云 ECS 服务器禁用了25端口,连接邮件服务器超时,导致出现 Mail server connection failed 异常
- 官方推荐使用465 端口,但是445端口是 SSL 协议,具体需要以下配置
JavaMailSender 配置
spring.mail.username=邮箱
spring.mail.password=开启POP3/SMTP服务时返回的密码
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
SSL 配置
spring.mail.port=465
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
# 开启加密验证,qq邮件需要
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
这样就可以正常在 阿里云服务器 上访问邮件服务器了!
三、定时任务
- 在主启动类开启定时任务注解 @EnableScheduling
- cron表达式(百度有在线生产器)
- 在方法上加注解 @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("你被执行了");
}
}