1、异步任务
在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。
两个注解:
@EnableAysnc、@Aysnc
@EnableAsync//开启异步注解功能@Servicepublic class AsyncService {//告诉springBoot这是一个异步方法@Asyncpublic void hello(){try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("处理数据中");}}@RestControllerpublic class AsyncController {@AutowiredAsyncService asyncService;@GetMapping("/hello")public String hello(){asyncService.hello();return "success";}}
2、定时任务
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor、TaskScheduler接口。
两个注解:@EnableScheduling、@Scheduled
cron表达式:

/*** <ul>* <li>second</li>* <li>minute</li>* <li>hour</li>* <li>day of month</li> 每个月的几号* <li>month</li>* <li>day of week</li>* </ul>** <p>For example, {@code "0 * * * * MON-FRI"} means once per minute on weekdays</p>** 0 0/5 14,18 * * ? 每天 14 点和 18 点 五分钟执行一次* 0 15 10 ? * 1-6 每个月的 周一到周六 的 10:15 执行一次* 0 0 2 ? * 6L 每个月的最后一个周六凌晨两点执行* 0 0 2 LW * ? 每个月的最后一个工作日 2:00* 0 0 2-4 ? * 1#1 每个月的第一周 2:00-4:00 整点执行*///@Scheduled(cron = "0 * * * * MON-FRI")//@Scheduled(cron = "0,1,2,3,4 * * * * MON-FRI")//@Scheduled(cron = "0-4 * * * * MON-FRI")@Scheduled(cron = "0/4 * * * * MON-FRI")//每 4s 执行一次public void hello(){System.out.println("hello---");}
3、邮件任务
•邮件发送需要引入spring-boot-starter-mail
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>

- 自己邮箱开启服务
- •Spring Boot 自动配置MailSenderAutoConfiguration
- •定义MailProperties内容,配置在application.yml中 ```java spring.mail.username=2778666783@qq.com spring.mail.password=bfzjxpqfaaclddcb spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
- •自动装配JavaMailSender- •测试邮件发送```java@AutowiredJavaMailSenderImpl mailSender;@Testvoid contextLoads() {SimpleMailMessage msg = new SimpleMailMessage();//邮件设置标题msg.setSubject("通知今晚开会");msg.setText("今晚7:30开会");msg.setTo("nkf15105201014@163.com");msg.setFrom("2778666783@qq.com");mailSender.send(msg);}
复杂邮件
@Testpublic void test() throws MessagingException, FileNotFoundException {//1、创建一个复杂的消息邮件MimeMessage mimeMessage = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);//邮件设置标题helper.setSubject(data(new Date()));helper.setText("<b style='color:red'>好好学习天天向上</b>");//上传附件helper.addAttachment("1.jpg",ResourceUtils.getFile("classpath:" + "static/img/1.jpg"));helper.addAttachment("2.jpg",ResourceUtils.getFile("classpath:" + "static/img/2.jpg"));helper.addAttachment("3.jpg",ResourceUtils.getFile("classpath:" + "static/img/3.jpg"));helper.setTo("2182908911@qq.com");helper.setFrom("2778666783@qq.com");mailSender.send(mimeMessage);System.out.println("发送成功");}

