ThreadPoolConfig.java 2.0 KB

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