异步任务
假设在Service层中方法中逻辑的执行需要一段时间,那么用户在访问时,也会需要等待。
可以使用异步任务来解决用户访问时等待这种不友好的情况。
AsyncService
类
@Service
public class AsyncService {
//告诉Spring这是一个异步方法
@Async
public void hello(){
try{
Thread.sleep(3000);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理......");
}
}
AsyncController
类
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();
return "OK";
}
}
SpringbootTaskApplication
类
//开启异步注解功能
@EnableAsync
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
如果不开使用异步任务,那么客户会等待三秒才收到返回的"OK",而使用后,那么会开启一条线程来执行Service层中的异步任务。
邮件任务
application.yaml
进行配置
spring:
mail:
#username中设置邮箱
username: 123456@163.com
#password中设置QQ邮箱中获取的密码
password: abcdefg
host: smtp.qq.com
#开启加密授权验证(QQ存在)
properties:
mail:
smtp:
ssl:
enable: true
简单邮件
测试类SpringbootTaskApplicationTests
@SpringBootTest
class SpringbootTaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("好好学Java");
mailMessage.setText("只要学不死,就往死里学");
//设置邮件接收方
mailMessage.setTo("ezer1999@163.com");
//设置邮件发送方
mailMessage.setFrom("123456@qq.com");
mailSender.send(mailMessage);
}
}
复杂邮件
测试类SpringbootTaskApplicationTests
@SpringBootTest
class SpringbootTaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("好好学Java~");
//可以开启解析html标签
helper.setText("<p style='color:red'>只要学不死,就往死里学<p>",true);
//附件
helper.addAttachment("test.jpg",new File("C:\\Users\\Lenovo\\Desktop\\test.jpg"));
//设置邮件接收方
helper.setTo("ezer1999@163.com");
//设置邮件发送方
helper.setFrom("123456@qq.com");
mailSender.send(mimeMessage);
}
}
定时任务
首先使用@EnableScheduling
注解标注SpringbootTaskApplication
类
//开启定时功能的注解
@EnableScheduling
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
@Service
public class ScheduledService {
//在@Scheduled中的cron属性中输入cron表达式,用来指定什么时候执行任务
//秒 分 时 日 月 周几
/*
cron = "0 40 9 * * 0-7":星期一到星期天的9点40分0秒执行
cron = "0 0/5 9,10 * * ?":每天9点或10点,每隔五分钟执行
*/
@Scheduled(cron = "0 0/5 9,10 * * 0-7")
public void hello(){
System.out.println("Hello SpringBoot");
}
}