package com;

import com.sv.netty.config.SpringContextHolder;
import com.sv.netty.netty.BootService;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

@SpringBootApplication
@EnableScheduling
@EnableAsync
@MapperScan(value = {"com.sv.mapper"})
public class NettyApplication {

	private static Logger logger = LoggerFactory.getLogger(NettyApplication.class);

	public static void main(String[] args) {
		logger.debug("应用启动成功...");
		ConfigurableApplicationContext context = SpringApplication.run(NettyApplication.class, args);
		SpringContextHolder.setContext(context);
		//启动netty
		BootService bootService = (BootService) context.getBean("bootService");
		bootService.run();

		//启动任务队列，处理
//		QueueTaskQueueDaemonThread queueTaskQueueDaemonThread = (QueueTaskQueueDaemonThread) context.getBean("queueTaskQueueDaemonThread");
//		queueTaskQueueDaemonThread.init();
	}

	private int corePoolSize = 5;//线程池维护线程的最少数量

	private int maxPoolSize = 15;//线程池维护线程的最大数量

	private int queueCapacity = 5; //缓存队列

	private int keepAlive = 60;//允许的空闲时间


	@Bean("scheduledExecutorService")
	public ScheduledExecutorService initScheduledExecutorService() {
		ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(400,
				new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
		return executorService;
	}

	@Bean
	public Executor executor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(corePoolSize);
		executor.setMaxPoolSize(maxPoolSize);
		executor.setQueueCapacity(queueCapacity);
		executor.setThreadNamePrefix("mqExecutor-");
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
		executor.setKeepAliveSeconds(keepAlive);
		executor.initialize();
		return executor;
	}

}
