package com.jwipc.log.config;

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.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author qizhicai
 * @version JDK 1.8
 * @date 2025/11/21
 * @description TODO
 */
@Configuration
@EnableAsync
public class AsyncAuditLogConfig {
    @Bean(name = "auditLogExecutor")
    public Executor auditLogExecutor() {
        // 服务器配置：8核16G，取 CPU 核心数的一半（4核）
        int serverCores = 8; // 明确指定服务器核心数（也可动态获取）
        int halfCores = serverCores / 2; // 4 核
        // 线程池参数（保守配置）
        int corePoolSize = halfCores; // 核心线程数 = 4
        int maxPoolSize = halfCores;  // 最大线程数 = 4（不动态扩展）
        int queueCapacity = 500;      // 队列容量（适中，避免内存溢出）
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("AuditLog-Async-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60); // 关闭等待时间
        executor.initialize();

        return executor;
    }
}
