如何开启异步调用在SpringBoot中,只需要在方法上加上@Async注解,就可以将同步方法变成异步调用。首先在启动类中添加@EnableAsync,开启异步调用。/***@authorqcy*/@SpringBootApplication@EnableAsyncpublicclassAsyncApplication{publicstaticvoidmain(String[]args){SpringApplication.run(AsyncApplication.class,args);}}在需要调用的方法中添加@Async注解packagecom.yang异步地。异步;importlombok.extern.slf4j.Slf4j;importorg.springframework.scheduling.annotation.Async;importorg.springframework.scheduling.annotation.AsyncResult;importorg.springframework.stereotype.Component;importjava.util.concurrent.Future;importjava.util。concurrent.FutureTask;/***@authorqcy*@create2020/09/0914:01:35*/@Slf4j@ComponentpublicclassTask{@Asyncpublicvoidmethod1(){log.info("method1启动,执行线程为"+Thread.currentThread().getName());try{Thread.sleep(2000);}catch(InterruptedExceptione){e.printStackTrace();}log.info("method1end");}@Asyncpublicvoidmethod2(){log.info("method2开始,执行线程为"+Thread.currentThread().getName());try{Thread.sleep(3000);}catch(InterruptedExceptione){e.printStackTrace();}log.info("method2结束");}}测试一next:@SpringBootTest@Slf4jpublicclassAsyncApplicationTests{@AutowiredTasktask;@TestpublicvoidtestAsyncWithVoidReturn()throwsInterruptedException{log.info("mainthreadstarts");task.method1();task.method2();//确保两个异步调用都执行到完成线程。sleep(6000);log.info("mainthreadend");}}输出结果如下:可以看出,SpringBoot创建了一个名为applicationTaskExecutor的线程池,并使用其中的线程执行异步调用。这里值得注意的是,不要在一个类中调用@Async标记的方法,否则将起不到异步调用的作用。至于为什么会出现这样的问题,需要深入源码去了解,我会另开一页。既然默认使用了SpringBoot创建的applicationTaskExecutor,那么如何自己定义一个线程池呢?自定义线程池,我们需要手动创建一个名为asynTaskExecutordcom.yang.async;importlombok.extern.slf4j.Slf4j;importorg的Beanpackage。springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.core.task.AsyncTaskExecutor;importorg.springframework.scheduling.concurrent.ThreadPoolTask??Executor;importjava.util.concurrent.ThreadPool***Executor;/@authorqcy*@create2020/09/0915:31:07*/@Slf4j@ConfigurationpublicclassAsyncConfig{@BeanpublicAsyncTaskExecutorasyncTaskExecutor(){ThreadPoolTask??Executorexecutor=newThreadPoolTask??Executor();executor.setCorePoolSize(8);executor.setMaxPoolSize(16);exeueCapacity(QueueCapacity50);executor.setAllowCoreThreadTimeOut(true);executor.setKeepAliveSeconds(10);executor.setRejectedExecutionHandler(newThreadPoolExecutor.CallerRunsPolicy());executor.setThreadNamePrefix("async-thread-pool-thread");returnexecutor;理解同学们可以参考我的文章讲一下线程池的其他类不用改,直接运行刚才的testAsyncWithVoidReturn()方法即可,输出:可以看出现在是我们自定义的线程池了.如果关心异步调用的返回值,如何处理?获取异步调用的返回结果要获取异步调用的结果,需要用到Future机制。可以参考我的另一篇文章讲Runnable、Future、Callable、FutureTask的关系。在Task类中添加如下两个方法:@AsyncpublicFuture
