package com.kym.admin.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步任务配置类
 * 使用 Java 21 虚拟线程优化异步任务执行
 */
@Configuration
@Slf4j
public class AsyncConfig {

    /**
     * 使用虚拟线程的异步执行器（推荐）
     * 虚拟线程非常轻量，适合高并发I/O密集型任务
     */
    @Bean("AsyncExecutor")
    public Executor customAsyncExecutor() {
        log.info("初始化异步虚拟线程执行器 - 使用 Java 21 Virtual Threads");
        var virtualThreadExecutor = Executors.newThreadPerTaskExecutor(Thread.ofVirtual()
                .name("async-vt-", 0)
                .factory());
        return new TaskExecutorAdapter(virtualThreadExecutor);
    }

    /**
     * 传统线程池执行器（作为备用方案保留）
     * 如需切换回传统线程池，请将上面的 @Bean 注解注释，并启用此方法
     */
    // @Bean("AsyncExecutor")
    public Executor traditionalAsyncExecutor() {
        log.info("初始化传统线程池执行器");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(1<<10);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("async-exec-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }
}
