peng
2026-03-18 e59a0201057ba67cad425fed804c82ff4ba0c6f1
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
package com.tievd.jyz.config;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
 
/**
 * 默认async线程池配置类
 * @author timi
 */
@Slf4j
@EnableAsync
@Configuration
public class DefaultAsyncConfig implements AsyncConfigurer {
    @Value("${init.pool.default.corePoolSize:10}")
    private Integer corePoolSize;
    @Value("${init.pool.default.maxPoolSize:20}")
    private Integer maxPoolSize;
    @Value("${init.pool.default.queueCapacity:10000}")
    private Integer queueCapacity;
    @Value("${init.pool.default.keepAliveSeconds:100}")
    private Integer keepAliveSeconds;
 
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //队列大小
        executor.setQueueCapacity(queueCapacity);
        //线程最大空闲时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix("default-async-Executor-");
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
                long submitted = threadPoolExecutor.getTaskCount();
                long completed = threadPoolExecutor.getCompletedTaskCount();
                log.error("默认线程池已满,丢弃!任务总数:{},未完成任务数:{}",submitted,(submitted-completed));
            }
        });
        executor.initialize();
        return executor;
    }
 
    /**
     * 异常处理器
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
         return new AsyncUncaughtExceptionHandler() {
 
            @Override
            public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) {
                log.error("=========================="+arg0.getMessage()+"=======================", arg0);
                log.error("exception method:"+arg1.getName());
            }
        };
    }
 
}