package com.ho.flow.config;

import com.alibaba.druid.support.http.StatViewServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author fancl
 * @desc: 线程池配置类
 * @date 2022/9/12
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Autowired
    DataSource dataSource;

    @PostConstruct
    public void t(){
        System.out.println();
    }

    @Bean
    ThreadPoolTaskExecutor flowThreadPoolExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int core = Runtime.getRuntime().availableProcessors();
        log.info("core:" +core);
        executor.setCorePoolSize(core);
        //最大线程数是核心线程数10倍
        executor.setMaxPoolSize(core * 10);
        //
        executor.setKeepAliveSeconds(600);
        executor.setQueueCapacity(core * 1000);
        executor.setThreadNamePrefix("flow-thread-execute");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }

    @Bean
    ServletRegistrationBean regisDruid() {
        //固定写法，配置访问路径
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //配置登录信息，固定写法
        HashMap<String, String> initParams = new HashMap<>();
        //账号和密码的key是固定的
        initParams.put("loginUsername", "fan");
        initParams.put("loginPassword", "111111");

        //允许谁可以访问
        initParams.put("allow", "");
        bean.setInitParameters(initParams);
        return bean;
    }
}
