zjh
2025-02-15 dc3cb5dea834cde14d1b527c22b35f1d5faebd5a
ltkj-admin/src/main/java/com/ltkj/web/config/timer/ThreadPoolConfiguration.java
@@ -2,7 +2,11 @@
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;
@@ -18,13 +22,38 @@
@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<Runnable>(10000),
                new LinkedBlockingQueue<>(10000),
                new ThreadFactoryBuilder().setNameFormat("default-executor-%d").build(),
                (r, executor) -> log.error("system pool is full! "));
                (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();
                        }
                    }
                });
            }
        };
    }
}
}