package com.seer.teach.openapi.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcAsyncConfig implements WebMvcConfigurer {

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 动态获取CPU核心数
        int cores = Runtime.getRuntime().availableProcessors();

        // 根据核心数动态计算线程池参数
        // 核心线程数 = CPU 核心数
        int corePoolSize = cores;
        // 最大线程数 = 核心数 * 5
        int maxPoolSize = cores * 5;
        // 队列容量 = 核心数 * 50
        int queueCapacity = cores * 50;

        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("mvc-async-");
        executor.initialize();

        configurer.setTaskExecutor(executor);
        configurer.setDefaultTimeout(30_000);
    }
}
