package com.njcn.gather.systemops.database.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 数据库运维后台任务线程池。
 */
@Slf4j
@Configuration
public class DbmsExecutorConfig {

    @Bean(name = "dbmsTaskExecutorService", destroyMethod = "shutdown")
    public ExecutorService dbmsTaskExecutorService() {
        AtomicInteger threadIndex = new AtomicInteger(1);
        return new ThreadPoolExecutor(
                1,
                1,
                30,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(8),
                runnable -> {
                    Thread thread = new Thread(runnable);
                    thread.setName("dbms-task-" + threadIndex.getAndIncrement());
                    return thread;
                },
                (runnable, executor) -> log.warn("数据库运维任务线程池已满，拒绝新的任务")
        );
    }
}
