CompletableFuture在springboot中使用
声明一个线程池
创建一个配置类,声明一个执行器的bean,使用@EnableAsync注解开启spring异步方法执行
/**
* @author Jenson 2020-08-18
*/
@Configuration
@EnableAsync
public class AsyncConfiguration {
/**
* 声明一个线程池
*
* @return 执行器
*/
@Bean("executorBeanName")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数5:线程池创建时候初始化的线程数
executor.setCorePoolSize(5);
//最大线程数5:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
executor.setMaxPoolSize(5);
//缓冲队列500:用来缓冲执行任务的队列
executor.setQueueCapacity(500);
//允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(60);
//线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
executor.setThreadNamePrefix("async01-");
executor.initialize();
return executor;
}
}
创建异步方法
@Async注解声明异步方法,参数传入执行器Bean名称
@Async("executorBeanName")
public CompletableFuture<List<String>> doSomeThingAsync(List<String> strList) {
logger.info("doSomeThingAsync");
// do some thing ...
return CompletableFuture.completedFuture(strList);
}
调用异步方法
注意:调用的函数和异步函数不能处于同一个实现类中
public List<WoForecast> callDoSomeThingAsync(List<String> strList) {
//复杂一点的情况,将strList拆成n个字符串列表List<List<String>> strLstList
// 分成n个循环调用异步函数
CompletableFuture[] completableFutureArr = new CompletableFuture[strLstList.size()];
strLstList.forEach(strLst -> {
CompletableFuture<List<String>> strLstFuture = doSomeThingAsync(strLst);
// 获取返回结果
completableFutureArr[strLstList.indexOf(strLst)] = strLstFuture;
});
//join() 的作用:让“主线程”等待“子线程”结束之后才能继续运行
CompletableFuture.allOf(completableFutureArr).join();
return strList;
}
网友评论