1. import lombok.extern.slf4j.Slf4j;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.scheduling.annotation.EnableAsync;
    5. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    6. import java.util.concurrent.Executor;
    7. import java.util.concurrent.ThreadPoolExecutor;
    8. @Configuration
    9. @EnableAsync
    10. @Slf4j
    11. public class ExecutorConfig {
    12. @Bean(name ="threadPool")
    13. public Executor asyncServiceExecutor() {
    14. log.info("================== start asyncServiceExecutor ==================");
    15. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    16. executor.setCorePoolSize(4);
    17. executor.setMaxPoolSize(8);
    18. executor.setQueueCapacity(50000);
    19. executor.setKeepAliveSeconds(60);
    20. //配置线程池中的线程的名称前缀
    21. executor.setThreadNamePrefix("thread-synchronization-runner-%d");
    22. // rejection-policy:当pool已经达到max size的时候,如何处理新任务
    23. // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
    24. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    25. //执行初始化
    26. executor.initialize();
    27. return executor;
    28. }
    29. /**
    30. * IO密集型线程池配置,此线程池多用于网络请求,磁盘IO。对CPU计算资源消耗娇小
    31. * @return
    32. */
    33. @Bean(name ="ioThreadPool")
    34. public Executor IOIntensiveExecutor() {
    35. log.info("================== start IOIntensiveExecutor ==================");
    36. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    37. executor.setCorePoolSize(20);
    38. executor.setMaxPoolSize(30);
    39. executor.setQueueCapacity(300000);
    40. executor.setKeepAliveSeconds(60);
    41. //配置线程池中的线程的名称前缀
    42. executor.setThreadNamePrefix("IO-Thread-synchronization-runner-%d");
    43. // rejection-policy:当pool已经达到max size的时候,如何处理新任务
    44. // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
    45. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    46. //执行初始化
    47. executor.initialize();
    48. return executor;
    49. }
    50. }