guoyujie
4 天以前 130fe64dd3eb0617ddc1f38afcd07656d56db27c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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 <T> 返回类型
     * @return CompletableFuture<T>
     */
    public <T> CompletableFuture<T> runAsync(SupplierWithException<T> 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> {
        T get() throws Exception;
    }
}