-
异步方法返回值只有两种情况,
void
或Future
对象; -
添加线程池配置:
thread-pool: max-pool-size: 50 core-pool-size: 20 queue-capacity: 2000 keep-alive-seconds: 120
-
创建配置类:
@EnableAsync @Configuration public class AsyncConfig { /** * 线程池的最大池大小,默认为 Integer.MAX_VALUE */ @Value("${thread-pool.max-pool-size:20}") private int MAX_POOL_SIZE; /** * 线程池的核心池大小,默认为 1 */ @Value("${thread-pool.core-pool-size:10}") private int CORE_POOL_SIZE; /** * 队列容量大小,默认为 Integer.MAX_VALUE */ @Value("${thread-pool.queue-capacity:200}") private int QUEUE_CAPACITY; /** * 生命周期,默认为 60,单位:秒 */ @Value("${thread-pool.keep-alive-seconds:60}") private int KEEP_ALIVE_SECONDS; /** * 线程池 * * @return asyncExecutor */ @Bean(name = "asyncExecutor") public AsyncTaskExecutor asyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setMaxPoolSize(MAX_POOL_SIZE); executor.setCorePoolSize(CORE_POOL_SIZE); executor.setQueueCapacity(QUEUE_CAPACITY); executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS); executor.setThreadNamePrefix("thread-pool-"); // rejection-policy:当pool已经达到max size的时候,如何处理新任务 // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //执行初始化 executor.initialize(); return executor; } /** * 执行周期性或定时任务 * * @return scheduledExecutorService */ @Bean(name = "scheduledExecutorService") protected ScheduledExecutorService scheduledExecutorService() { BasicThreadFactory build = new BasicThreadFactory.Builder() .namingPattern("schedule-pool-%d") .daemon(true) .build(); return new ScheduledThreadPoolExecutor(CORE_POOL_SIZE, build) { @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); ThreadUtils.printException(r, t); } }; } }
-
线程池的使用:
-
注入执行器使用:
@Autowired private AsyncTaskExecutor asyncExecutor; public CompletableFuture<AjaxResult> demo1() throws Exception { // Runnable接口无需返回值 asyncExecutor.execute(() -> { ThreadUtils.sleep(1000); System.out.println("Runnable接口"); }); // Callable接口返回值为Future类型 Future<AjaxResult> submit = asyncExecutor.submit(() -> { ThreadUtils.sleep(1000); System.out.println("Callable接口"); return AjaxResult.success("Callable接口"); }); return submit; }
-
CompletableFuture
调用:@Autowired private AsyncTaskExecutor asyncExecutor; /** * 使用注入的线程池对象,执行异步方法 */ public CompletableFuture<AjaxResult> demo2() { // supplyAsync首先执行此线程 return CompletableFuture.supplyAsync(studentMapper::selectAll, asyncExecutor) // supplyAsync执行完成后,紧接着执行thenApply线程方法 .thenApply(res -> { ThreadUtils.sleep(1000); System.out.println("CompletableFuture对象实现异步"); return AjaxResult.success(res.stream() .map(Student::getGuid) .collect(Collectors.toList()) ); }); }
-
spring异步注解
@Async
:/** * 指定线程池对象去执行 */ @Async("asyncExecutor") public CompletableFuture<AjaxResult> demo3() { ThreadUtils.sleep(1000); System.out.println("Async注解实现异步"); AjaxResult result = AjaxResult.success("Async注解实现异步"); return CompletableFuture.completedFuture(result); }
-
11-03
436