关于SpringBoot实现一些特定任务的方法
一、异步任务
1.1 使用环境
使用异步任务场景:Controller调用Service层方法,等Service方法结束后,才跳转页面。一旦业务处理时间过长,页面加载半天,导致用户体验差
- (1)配置线程池
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Configuration @EnableAsync public class AsyncConfiguration { @Bean("doSomethingExecutor") public Executor doSomethingExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(500); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("do-something-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); executor.initialize(); return executor; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| Service层方法 @Service public class AsynService {
public void waiting() {
System.out.println("数据处理中");
try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| Controller @Controller public class AsynController {
@Autowired AsynService service;
@RequestMapping("/hello") @ResponseBody public String hello() { service.waiting(); return "OK!"; }
}
|
- 访问该页面,返现加载3秒之后页面才显示出来,十分的慢
1.2 异步的使用
- (1)在需要开启异步的方法waiting()中添加注解
@Async
- (2)在SpringBoot主程序Application.java中开启异步
@EnableAsync
这时再访问该页面,发现页面秒打开,这就是开启异步后的现象
二、邮件任务
邮件任务即通过java程序来发送邮件
2.1 导入相关依赖
1 2 3 4 5
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
|
2.2 配置文件设置
1 2 3 4 5 6 7 8
| spring: mail: username: 190649799@qq.com password: jsdjxhpszzrfcehh host: smtp.qq.com properties: mail.smtl.ssl.enable: true
|
2.3 发送一个简单的邮件
创建一个信息类,通过JavaMailSenderImpl.send(信息类)来发送邮件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Autowired JavaMailSenderImpl mailSender;
@Test void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("邮件主题"); simpleMailMessage.setText("邮件内容"); simpleMailMessage.setTo("1906497996@qq.com"); simpleMailMessage.setFrom("1906497996@qq.com");
mailSender.send(simpleMailMessage);
}
|
2.4 发送一个复杂的邮件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Autowired JavaMailSenderImpl mailSender;
@Test void test() throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setSubject("主题"); helper.setText("<p style='color:red'>这是邮件的内容</p>", true);
helper.addAttachment("色图.jpg", new File("文件路径"));
helper.setTo("1906497996@qq.com"); helper.setFrom("1906497996@qq.com");
mailSender.send(message); }
|
三、定时任务
3.1 两个注解
@EnableScheduling
:开启定时功能的注解,在主程序Application.java中添加此注解
@Scheduled
: 方法执行的时间,在要定时执行的方法上添加此注解,注解参数为Cron表达式
3.2 Cron表达式
3.3 实例
1 2 3 4 5 6 7 8 9 10
| @Service public class ScheduledService {
@Scheduled(cron = "0 * * * * 0-7") public void Hello() { System.out.println("Hello! 你被执行了!"); } }
|