ThreadPoolConfig.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package com.ruoyi.framework.config;
  2. import java.util.concurrent.ScheduledExecutorService;
  3. import java.util.concurrent.ScheduledThreadPoolExecutor;
  4. import java.util.concurrent.ThreadPoolExecutor;
  5. import org.apache.commons.lang3.concurrent.BasicThreadFactory;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  9. import com.ruoyi.common.utils.Threads;
  10. /**
  11. * 线程池配置
  12. *
  13. * @author ruoyi
  14. **/
  15. @Configuration
  16. public class ThreadPoolConfig {
  17. // 核心线程池大小
  18. private int corePoolSize = 50;
  19. // 最大可创建的线程数
  20. private int maxPoolSize = 200;
  21. // 队列最大长度
  22. private int queueCapacity = 1000;
  23. // 线程池维护线程所允许的空闲时间
  24. private int keepAliveSeconds = 300;
  25. @Bean(name = "threadPoolTaskExecutor")
  26. public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
  27. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  28. executor.setMaxPoolSize(maxPoolSize);
  29. executor.setCorePoolSize(corePoolSize);
  30. executor.setQueueCapacity(queueCapacity);
  31. executor.setKeepAliveSeconds(keepAliveSeconds);
  32. // 线程池对拒绝任务(无线程可用)的处理策略
  33. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  34. return executor;
  35. }
  36. /**
  37. * 执行周期性或定时任务
  38. */
  39. @Bean(name = "scheduledExecutorService")
  40. protected ScheduledExecutorService scheduledExecutorService() {
  41. return new ScheduledThreadPoolExecutor(corePoolSize,
  42. new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) {
  43. @Override
  44. protected void afterExecute(Runnable r, Throwable t) {
  45. super.afterExecute(r, t);
  46. Threads.printException(r, t);
  47. }
  48. };
  49. }
  50. }