jiangqs
2023-06-07 bdc5a18e1715b6d0c7cc19da1a5d602de1f26893
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
76
77
78
79
80
81
package com.ruoyi.common.security.config;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
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.ThreadPoolExecutor;
 
/**
 * @ClassName AsyncConfig
 * @Description TODO
 * @Author jqs
 * @Date 2023/6/7 10:46
 * @Version 1.0
 */
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {
 
    /**
     * 表示线程池核心线程,正常情况下开启的线程数量
     */
    private Integer corePoolSize = 10;
 
    /**
     * 如果queueCapacity存满了,还有任务就会启动更多的线程,
     * 直到线程数达到maxPoolSize。如果还有任务,则根据拒绝策略进行处理
     */
    private Integer maxPoolSize = 100;
 
    /**
     * 当核心线程都在跑任务,还有多余的任务会存到此处
     */
    private Integer queueCapacity = 100;
 
    private Integer keepAliveSeconds = 60;
 
    private String threadNamePrefix = "async-thread-";
 
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //队列容量
        executor.setQueueCapacity(queueCapacity);
        //活跃时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //线程名字前缀
        executor.setThreadNamePrefix(threadNamePrefix);
 
        // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
        // CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    /**
     *  异步任务中异常处理
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
                log.info("==================线程发生错误=====================");
                log.error("=========================="+throwable.getMessage()+"=======================", throwable);
                log.error("exception method:"+method.getName());
            }
        };
    }
}