package kr.wisestone.owl.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.util.ErrorHandler; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; /** * Created by jeong on 2017-07-26. */ @Configuration @EnableScheduling @EnableAsync(order= Ordered.HIGHEST_PRECEDENCE) public class AsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer { private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); private static final String CORE_POOL_SIZE = "10"; private static final String MAX_POOL_SIZE = "100"; private static final String QUEUE_CAPACITY = "100000"; @Override @Bean(name = "taskExecutor") public ThreadPoolTaskExecutor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(Integer.parseInt(CORE_POOL_SIZE)); executor.setMaxPoolSize(Integer.parseInt(MAX_POOL_SIZE)); executor.setQueueCapacity(Integer.parseInt(QUEUE_CAPACITY)); executor.setThreadNamePrefix("owl-Executor-"); return executor; } @Bean public ThreadPoolTaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(20); scheduler.setThreadNamePrefix("task-"); scheduler.setAwaitTerminationSeconds(60); scheduler.setWaitForTasksToCompleteOnShutdown(true); scheduler.setErrorHandler(new ErrorHandler() { @Override public void handleError(Throwable t) { log.error("task 실행시 알 수 없는 에러가 발생했습니다.", t); } }); scheduler.setRejectedExecutionHandler(new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { log.error("알 수 없는 이유로 task 실행이 거절되었습니다.", r); } }); return scheduler; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { TaskScheduler taskScheduler = this.taskScheduler(); taskRegistrar.setTaskScheduler(taskScheduler); } }