puzhibing
2023-10-08 22199bbdda579861736420fe26c2873ab0f5d21c
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
package com.sinata.rest.modular.auth.util;
 
import com.sinata.rest.common.exception.BizExceptionEnum;
import com.sinata.rest.core.exception.GunsException;
import com.sinata.rest.modular.auth.model.AccountVo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import java.util.concurrent.ThreadPoolExecutor;
 
/**
 * 线程池
 *
 * @author: KingKong
 **/
@EnableAsync
@Configuration
public class ThreadPoolUtil {
 
    public final static ThreadLocal<AccountVo> ACCOUNT_LOCAL = new ThreadLocal<>();
 
    /**
     * 获取用户id
     *
     * @return
     */
    public static Integer getUserId() {
        AccountVo account = ACCOUNT_LOCAL.get();
        if (account == null) {
            throw new GunsException(BizExceptionEnum.AUTH_REQUEST_ERROR);
        }
        return account.getId();
    }
 
    @Bean("asyncThread")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(10);
        // 设置最大线程数
        executor.setMaxPoolSize(20);
        executor.setAllowCoreThreadTimeOut(true);
        // 设置队列容量
        executor.setQueueCapacity(50);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("KingKong-asyncThread-");
        // 设置拒绝策略
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }
}