zhaowenxuan
2025-02-15 9450b481614c7a4f191475d63cfa5c5a3f87141e
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
package com.ltkj.web.config.timer;
 
 
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.ltkj.framework.aspectj.AsynAspect;
import com.ltkj.framework.datasource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
 * @Company: 西安路泰科技有限公司
 * @Author: zjh
 * @Date: 2023/3/28 11:48
 */
 
@Configuration
@Slf4j
public class ThreadPoolConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(AsynAspect.class);
 
    @Bean(name = "async", destroyMethod = "shutdown")
    public ThreadPoolExecutor systemCheckPoolExecutorService() {
        // 获取当前线程的数据源
        String dataSource = DynamicDataSourceContextHolder.getDataSourceType();
        logger.info("异步传递线程当前线程数据源: {}", dataSource);
 
        return new ThreadPoolExecutor(3, 10, 60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10000),
                new ThreadFactoryBuilder().setNameFormat("default-executor-%d").build(),
                (r, executor) -> logger.error("system pool is full! ")) {
 
            @Override
            public void execute(Runnable task) {
                // 包装任务,将数据源传递到异步线程
                super.execute(new Runnable() {
                    @Override
                    public void run() {
                        // 在异步线程中设置数据源
                        String dataSource = DynamicDataSourceContextHolder.getDataSourceType();
                        try {
                            DynamicDataSourceContextHolder.setDataSourceType(dataSource);
                            task.run();
                        } finally {
                            // 确保在任务执行完成后清理数据源
                            DynamicDataSourceContextHolder.clearDataSourceType();
                        }
                    }
                });
            }
        };
    }
 
}