异步任务在我们的工作中,常常会用到异步处理任务,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。还有一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息。还有就是邮件的发送,微信的前身也是邮件服务呢?这些东西都是怎么实现的呢?其实SpringBoot都给我们提供了对应的支持,我们上手使用十分的简单,只需要开启一些注解支持,配置一些配置文件即可!那我们来看看吧~
异步处理还是非常常用的,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。
Spring要实现异步任务也分成简单,接下来我们来看一下
AsyncService
@Service
public class AsyncService {
@Async //标明它是一个异步方法
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("业务进行中....");
}
}
AsyncController
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class AsyncApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncApplication.class, args);
}
}
正常访问,页面会转圈转三秒,才相应显示success,而把他标注为异步任务,就能实现和多线程异步一样,直接显示了。
邮件任务第一步,同样,先引入依赖
org.springframework.boot spring-boot-starter-mail
编写配置文件
spring:
mail:
# 发件人的邮箱账号如:xxx@163.com
username: ********@qq.com
# 发件人的邮箱的授权码(自己在邮箱服务器中开启并设置)
password: hbnpaouyxvfrbaeb
# 发件人邮箱的SMTP服务器地址,如:smtp.163.com,我使用的是qq邮箱所以如下:
host: smtp.qq.com
# 开启加密验证
properties: {mail.smtl.ssl.enable: true}
获取授权码:在QQ邮箱中的设置->账户->开启pop3和smtp服务
测试
@SpringBootTest
class SpringBootLearnApplicationTests {
//用@Resource自动注入
@Resource
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("*************");
message.setText("************");
message.setTo("*********@qq.com");
message.setFrom("**********@qq.com");
mailSender.send(message);
}
@Test
public void contextLoads2() throws MessagingException {
//邮件设置2:一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("通知");
helper.setText("今天 7:30来开会",true);
//发送附件
helper.addAttachment("1.jpg",new File(""));
helper.addAttachment("2.jpg",new File(""));
helper.setTo("******@qq.com");
helper.setFrom("*******@qq.com");
mailSender.send(mimeMessage);
}
}
测试,发送了一封邮件。
我们在业务中的正常写法,将它封装成utils方法,然后在controller层调用,用thymeleaf进行前后端交互获取数据发送邮件。
定时任务项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,Spring为我们提供了异步执行任务调度的方式,提供了两个接口。
-
TaskExecutor接口 //任务执行者
-
TaskScheduler接口 //任务调度者
两个注解:
-
@EnableScheduling //开启定时功能的注解 主启动类上
-
@Scheduled //什么时候执行 方法上
@Service
public class ScheduledService {
//秒 分 时 日 月 周几
//0 * * * * MON-FRI
//注意cron表达式的用法;
@Scheduled(cron = "0 * * * * 0-7")
public void hello(){
System.out.println("hello.....");
}
}
cron表达式了解quartz/Cron/Crontab表达式在线生成工具-BeJSON.com



