任务
异步任务
在实际开发中,我们会遇到许多业务场景,例如发送邮件,我们点击发送邮件按钮后,立即会收到发送成功的信息,实际上发送邮件是一个耗时的过程,并不会立即发送成功,这是给我们返回的是一个假的发送成功的信息,而会专门开启一个线程处理邮件发送,像这样的任务称之为异步任务。
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();
return "ok";
}
}
@Service
public class AsyncService {
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( "任务执行中.....");
}
}
@EnableAsync
@SpringBootApplication
public class SpringBootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootTaskApplication.class, args);
}
}
案例中在启动类和service层的方法上加了@EnableAsync和@Async(加在service层才生效),表示方法开启了异步任务,这样在调用方法的时候会直接返回结果,而不会等待三秒。
邮件任务
发送邮件是一个常见的业务,spring中已经封装好了相关接口,springboot集成如下
首先导入依赖
<!--邮件任务-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置参数,这里使用qq邮箱为例
调用接口
@SpringBootTest
class SpringBootTaskApplicationTests {
@Autowired
JavaMailSenderImpl javaMailSender;
@Test
void contextLoads() {
//发送一个简单的任务
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("测试邮件发送springboot");
message.setText("好好学java");
message.setTo("1531756119@qq.com");
message.setFrom("1531756119@qq.com");
javaMailSender.send(message);
}
@Test
void contextLoads2() throws MessagingException {
//发送一个复杂的任务
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//正文
helper.setText("<P style='red'>没事多学习</p>");
helper.setSubject("测试一个复杂的邮件发送springboot");
//附件
helper.addAttachment("aa.jpg",new File("D:\\java\\aa.jpg"));
helper.setTo("1531756119@qq.com");
helper.setFrom("1531756119@qq.com");
javaMailSender.send(mimeMessage);
}
}
结果
定时任务
定时任务调度指的是基于给定的时间点、给定的时间间隔、给定的执行次数自动执行的任务。springboot提供了接口。
核心接口和注解:
TaskExecutor//任务执行者
TaskScheduler//任务调度者
@EnableScheduling //开启定时功能
@Scheduled //什么时候执行
@Service
public class SchedService {
//cron表达式,定义被执行的时间点
//表示每天的19点51分19秒被执行
@Scheduled(cron="50 51 19 * * ?")
public void hello(){
System.out.println("hello,我是定时任务,被执行啦");
}
}