ThreadPoolConfig.java 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package com.ruoyi.common.config.thread;
  2. import java.util.concurrent.CancellationException;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.Future;
  5. import java.util.concurrent.ScheduledExecutorService;
  6. import java.util.concurrent.ScheduledThreadPoolExecutor;
  7. import java.util.concurrent.ThreadPoolExecutor;
  8. import org.apache.commons.lang3.concurrent.BasicThreadFactory;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.context.annotation.Bean;
  12. import org.springframework.context.annotation.Configuration;
  13. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  14. /**
  15. * 线程池配置
  16. *
  17. * @author ruoyi
  18. **/
  19. @Configuration
  20. public class ThreadPoolConfig
  21. {
  22. private static final Logger log = LoggerFactory.getLogger(ThreadPoolConfig.class);
  23. // 核心线程池大小
  24. private int corePoolSize = 50;
  25. // 最大可创建的线程数
  26. private int maxPoolSize = 200;
  27. // 队列最大长度
  28. private int queueCapacity = 1000;
  29. // 线程池维护线程所允许的空闲时间
  30. private int keepAliveSeconds = 300;
  31. @Bean(name = "threadPoolTaskExecutor")
  32. public ThreadPoolTaskExecutor threadPoolTaskExecutor()
  33. {
  34. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  35. executor.setMaxPoolSize(maxPoolSize);
  36. executor.setCorePoolSize(corePoolSize);
  37. executor.setQueueCapacity(queueCapacity);
  38. executor.setKeepAliveSeconds(keepAliveSeconds);
  39. // 线程池对拒绝任务(无线程可用)的处理策略
  40. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  41. return executor;
  42. }
  43. /**
  44. * 执行周期性或定时任务
  45. */
  46. @Bean(name = "scheduledExecutorService")
  47. protected ScheduledExecutorService scheduledExecutorService()
  48. {
  49. return new ScheduledThreadPoolExecutor(corePoolSize,
  50. new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) {
  51. @Override
  52. protected void afterExecute(Runnable r, Throwable t) {
  53. super.afterExecute(r, t);
  54. if (t == null && r instanceof Future<?>) {
  55. try {
  56. Object result = ((Future<?>) r).get();
  57. } catch (CancellationException ce) {
  58. t = ce;
  59. } catch (ExecutionException ee) {
  60. t = ee.getCause();
  61. } catch (InterruptedException ie) {
  62. Thread.currentThread().interrupt(); // ignore/reset
  63. }
  64. }
  65. if(t != null) {
  66. log.error(t.getMessage());
  67. }
  68. }
  69. };
  70. }
  71. }