springboot 异步方法
作用:在一个方法内调用异步方法,原方法不阻塞继续运行,异步方法可异步执行
****************************
示例
******************
config 层
TaskExecutorConfig:配置异步线程池
@Configuration
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(10);
executor.setKeepAliveSeconds(10);
executor.initialize();
return executor;
}
}
******************
service 层
TaskService
@Service
public class TaskService {
public void task(){
System.out.println("task 开始运行:"+System.currentTimeMillis());
try{
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("task 运行结束:"+System.currentTimeMillis());
}
@Async
public void task2(){
System.out.println("task2 开始运行:"+System.currentTimeMillis());
try{
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("task2 运行结束:"+System.currentTimeMillis());
}
}
******************
controller 层
HelloController
@RestController
public class HelloController {
@Resource
private TaskService taskService;
@RequestMapping("/hello")
public String hello(){
System.out.println("开始调用task任务:"+System.currentTimeMillis());
taskService.task();
System.out.println("task任务调用结束:"+System.currentTimeMillis());
return "success";
}
@RequestMapping("/hello2")
public String hello2(){
System.out.println("开始调用task2任务:"+System.currentTimeMillis());
taskService.task2();
System.out.println("task2任务调用结束:"+System.currentTimeMillis());
return "success 2";
}
}
****************************
控制台输出
/hello
开始调用task任务:1577101307042
task 开始运行:1577101307042
task 运行结束:1577101308042
task任务调用结束:1577101308042
/hello2
开始调用task2任务:1577101309740
task2任务调用结束:1577101309741
task2 开始运行:1577101309741
task2 运行结束:1577101310754
任务task2以异步方式被调用