zjh
2025-02-20 b35cb9c705dae9b8fd256c93f9c57dac678f3a6e
ltkj-admin/src/main/java/com/ltkj/web/config/timer/ThreadPoolConfiguration.java
@@ -2,7 +2,12 @@
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.ltkj.db.DataSourceContextHolder;
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;
@@ -19,12 +24,36 @@
@Slf4j
public class ThreadPoolConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolConfiguration.class);
    @Bean(name = "async", destroyMethod = "shutdown")
    public ThreadPoolExecutor systemCheckPoolExecutorService() {
        // 获取当前线程的 DataSource
        String currentDataSource = DataSourceContextHolder.getDataSourceKey();
        logger.info("当前线程数据源: {}", currentDataSource);
        return new ThreadPoolExecutor(3, 10, 60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(10000),
                new LinkedBlockingQueue<>(10000),
                new ThreadFactoryBuilder().setNameFormat("default-executor-%d").build(),
                (r, executor) -> log.error("system pool is full! "));
                (r, executor) -> log.error("system pool is full! ")) {
            @Override
            public void execute(Runnable command) {
                // 包装任务,确保数据源被传递到新线程
                super.execute(() -> {
                    String dataSourceKey = DataSourceContextHolder.getDataSourceKey();
                    try {
                        // 传递数据源到子线程
                        DynamicDataSourceContextHolder.setDataSourceType(dataSourceKey);
                        command.run(); // 执行任务
                    } finally {
                        // 任务完成后清理数据源上下文
                        DynamicDataSourceContextHolder.clearDataSourceType();
                    }
                });
            }
        };
    }
}
}