#yyds干货盘点# springboot使用@Async实现异步调用

【#yyds干货盘点# springboot使用@Async实现异步调用】一万年来谁著史,三千里外欲封侯。这篇文章主要讲述#yyds干货盘点# springboot使用@Async实现异步调用相关的知识,希望能为你提供帮助。
springboot使用@Async实现异步调用
1.代码实现:
创建异步任务类

@Slf4j
@Component
public class AsyncTasks

public static Random random = new Random();

@Async
public CompletableFuture< String> doTaskOne() throws Exception
log.info("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务一,耗时:" + (end - start) + "毫秒");
return CompletableFuture.completedFuture("任务一完成");


@Async
public CompletableFuture< String> doTaskTwo() throws Exception
log.info("开始做任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务二,耗时:" + (end - start) + "毫秒");
return CompletableFuture.completedFuture("任务二完成");


@Async
public CompletableFuture< String> doTaskThree() throws Exception
log.info("开始做任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务三,耗时:" + (end - start) + "毫秒");
return CompletableFuture.completedFuture("任务三完成");





启动类添加异步注解
@EnableAsync
@SpringBootApplication
public class AsyncTaskApplication

public static void main(String[] args)
SpringApplication.run(AsyncTaskApplication.class, args);






测试类
@Slf4j
@SpringBootTest
class AsyncTaskApplicationTests

@Autowired
private AsyncTasks asyncTasks;

@Test
void contextLoads()


@Test
public void Test() throws Exception
long start = System.currentTimeMillis();

CompletableFuture< String> task1 = asyncTasks.doTaskOne();
CompletableFuture< String> task2 = asyncTasks.doTaskTwo();
CompletableFuture< String> task3 = asyncTasks.doTaskThree();

CompletableFuture.allOf(task1, task2, task3).join();

long end = System.currentTimeMillis();

log.info("任务全部完成,总耗时:" + (end - start) + "毫秒");



2.实现效果:
2021-12-29 16:23:10.176INFO 7500 --- [main] c.c.a.AsyncTaskApplicationTests: Started AsyncTaskApplicationTests in 1.054 seconds (JVM running for 3.159)
2021-12-29 16:23:10.613INFO 7500 --- [task-2] com.cxh.async_task.task.AsyncTasks: 开始做任务二
2021-12-29 16:23:10.613INFO 7500 --- [task-1] com.cxh.async_task.task.AsyncTasks: 开始做任务一
2021-12-29 16:23:10.614INFO 7500 --- [task-3] com.cxh.async_task.task.AsyncTasks: 开始做任务三
2021-12-29 16:23:14.654INFO 7500 --- [task-2] com.cxh.async_task.task.AsyncTasks: 完成任务二,耗时:4041毫秒
2021-12-29 16:23:15.138INFO 7500 --- [task-3] com.cxh.async_task.task.AsyncTasks: 完成任务三,耗时:4524毫秒
2021-12-29 16:23:15.873INFO 7500 --- [task-1] com.cxh.async_task.task.AsyncTasks: 完成任务一,耗时:5259毫秒
2021-12-29 16:23:15.874INFO 7500 --- [main] c.c.a.AsyncTaskApplicationTests: 任务全部完成,总耗时:5320毫秒

可以看到,通过异步调用,让任务一、二、三并发执行,有效的减少了程序的总运行时间。

    推荐阅读