SpringBoot 异步调用:
1.在方法中使用@Async注解,表示该方法是异步方法
@Component
public class Task {
@Async("mytask")
public Future workerTask() throws InterruptedException {
Random random = new Random();
System.out.println("workerTask()方法开始执行");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("workerTask()方法执行结束,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("workerTask()方法执行结束 \n");
}
@Async("mytask")
public Future masterTask() throws InterruptedException {
Random random = new Random();
System.out.println("masterTask()方法开始执行");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("masterTask()方法执行结束,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("masterTask()方法执行结束 \n");
}
@Async("mytask")
public Future orderTask() throws InterruptedException {
Random random = new Random();
System.out.println("orderTask()方法开始执行");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("orderTask()方法执行结束,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("orderTask()方法执行结束 \n");
}
}
2.使用Future对异步任务进行管理,isDone()方法表示异步任务执行结束
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAsyncDemoApplicationTests {
@Autowired
private Task task;
@Test
public void contextLoads() throws InterruptedException {
}
@Test
public void testTask() throws Exception {
long start = System.currentTimeMillis();
Future worker = task.workerTask();
Future master = task.masterTask();
Future order = task.orderTask();
while (true) {
if (worker.isDone() && master.isDone() && order.isDone()) {
System.out.println("异步任务执行结束");
break;
}
Thread.sleep(1000);
}
long end = System.currentTimeMillis();
System.out.println("所有方法执行结束,耗时:" + (end - start) + "毫秒");
}
}
3.springboot项目入口使用注解@EnableAsync开启异步调用,并使用TaskExecutor配置@Bean让@Async生效
@SpringBootApplication
@EnableAsync
public class SpringAsyncDemoApplication {
/**
* 必须配置,否则Async注解失效
*
* @return
* @date 2017/12/13
*/
@Bean(name = "mytask")
public TaskExecutor workExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("Async-");
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setMaxPoolSize(20);
threadPoolTaskExecutor.setQueueCapacity(600);
threadPoolTaskExecutor.afterPropertiesSet();
return threadPoolTaskExecutor;
}
public static void main(String[] args) {
SpringApplication.run(SpringAsyncDemoApplication.class, args);
}
}
4.运行测试类,结果显示:
workerTask()方法开始执行
masterTask()方法开始执行
orderTask()方法开始执行
orderTask()方法执行结束,耗时:4054毫秒
workerTask()方法执行结束,耗时:5054毫秒
masterTask()方法执行结束,耗时:9233毫秒
异步任务执行结束
所有方法执行结束,耗时:10039毫秒