任务
1、异步任务
同步任务就是,A调用了B方法,必须要得B执行完了之后才能执行,如果B方法执行的很慢,A页必须等待。
鉴于这种方法有时候会很低效,所以就有了异步执行,A调用B方法之后,会再开一个线程去执行B,不会影响A的执行。
在SpringBoot中要想实现异步任务十分简单,接下来我们先写一个不是异步方法的代码,
@Service
public class AsyncService {
public void hello() throws InterruptedException {
Thread.sleep(5000); //测试方法,我们让线程失眠5秒
System.out.println("处理数据中...");
}
}
编写controller
层如下:
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello() throws InterruptedException {
asyncService.hello(); //调用同步方法
return "hello";
}
}
运行项目,在浏览器中输入 http://localhost:8080/hello
,可以看到在过了 5 秒之后才会输出 hello
。
现在我们来更改 AsyncService.java
中的代码:
@Service
public class AsyncService {
//告诉Spring这是一个异步方法
@Async
public void hello() throws InterruptedException {
Thread.sleep(5000);
System.out.println("处理数据中...");
}
}
并且在 UmserverApplication.java
中开启异步注解:
@SpringBootApplication
@EnableAsync
public class UmserverApplication {
public static void main(String[] args) {
SpringApplication.run(UmserverApplication.class, args);
}
}
再次执行,就可以马上看到 hello
,但是在 5 秒之后控制台输出 处理数据中...
。
1.1 配置
如果你在
context
中定义了一个Executor
,那么异步任务就会使用它。
线程池使用8个核心线程,当然也会根据任务的多少增加或者减少。这些默认的配置能够使用 spring.task.execution
命名空间来调整,例如:
spring.task.execution.pool.max-size=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s
上面的配置使线程池使用了一个受限的 queue
,当 queue
满的时候(达到了100个任务),线程数就会增加,但是最大也只会到 16 个。线程空闲10 秒(而不是默认的 60 秒)时,线程就会被回收。
2、定时任务
要使用定时任务也是十分的简单,如下:
在方法上添加上 @Scheduled
注解,
@Service
public class MailSend {
/*cron的详细配置请看下面*/
@Scheduled(cron = "0-4 * * * * 1-6")
public void hello() throws InterruptedException {
System.out.println("hello...");
}
}
并且在 UmserverApplication.java
中添加上 @EnableScheduling
注解即可。
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class UmserverApplication {
public static void main(String[] args) {
SpringApplication.run(UmserverApplication.class, args);
}
}
启动项目后,在每分钟的 0-4
秒时控制台会打印 hello...
。
关于 cron
的值:
字段 | 允许值 | 允许的特殊字符 |
---|---|---|
秒 | 0-59 | , - * / |
分 | 0-59 | , - * / |
小时 | 0-23 | , - * / |
日期 | 1-31 | , - * ? / L W C |
月份 | 1-12 | , - * / |
星期 | 1-7 | , - * ? / L C # |
特殊字符 | 代表含义 |
---|---|
, | 枚举 |
- | 区间 |
* | 任意 |
/ | 步长 |
? | 日/星期冲突匹配 |
L | 最后 |
W | 工作日 |
C | 和calendar联系后计算过的值 |
# | 星期, 4#2 ,第2个星期四 |