package com.example.erp.common; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.util.concurrent.*; /** * 全局异步查询执行器 * 统一管理线程池,支持在多个 Service 并行执行 SQL 查询任务 */ @Component public class AsyncQueryExecutor { // 全局可复用线程池 private final ExecutorService executorService = new ThreadPoolExecutor( 16, // 核心线程数 32, // 最大线程数 60L, TimeUnit.SECONDS, // 空闲线程存活时间 new LinkedBlockingQueue<>(500), // 阻塞队列容量 new ThreadFactory() { private final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); private int counter = 1; @Override public Thread newThread(Runnable r) { Thread thread = defaultFactory.newThread(r); thread.setName("async-query-pool-" + counter++); thread.setDaemon(true); return thread; } }, new ThreadPoolExecutor.CallerRunsPolicy() // 队列满时主线程执行,防止丢任务 ); /** * 异步执行任务 * @param supplier 要执行的函数(返回任意类型) * @param 返回类型 * @return CompletableFuture */ public CompletableFuture runAsync(SupplierWithException supplier) { return CompletableFuture.supplyAsync(() -> { try { return supplier.get(); } catch (Exception e) { throw new RuntimeException("异步任务执行异常: " + e.getMessage(), e); } }, executorService); } /** * 应用关闭时安全关闭线程池 */ @PreDestroy public void shutdown() { executorService.shutdown(); try { if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { executorService.shutdownNow(); } } catch (InterruptedException e) { executorService.shutdownNow(); Thread.currentThread().interrupt(); } } /** * 自定义函数式接口,允许抛出受检异常 */ @FunctionalInterface public interface SupplierWithException { T get() throws Exception; } }