AsyncTaskPoolConfig.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package cn.cslg.pas.common.config;
  2. import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.core.task.AsyncTaskExecutor;
  6. import org.springframework.scheduling.annotation.AsyncConfigurer;
  7. import org.springframework.scheduling.annotation.EnableAsync;
  8. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  9. import java.util.concurrent.Executor;
  10. import java.util.concurrent.ThreadPoolExecutor;
  11. @EnableAsync
  12. @Configuration
  13. public class AsyncTaskPoolConfig implements AsyncConfigurer {
  14. @Bean("singleThreadAsyncTaskExecutor")
  15. public AsyncTaskExecutor singleThreadAsyncTaskExecutor() {
  16. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  17. executor.setCorePoolSize(1);
  18. executor.setMaxPoolSize(1);
  19. executor.setQueueCapacity(64);
  20. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  21. executor.initialize();
  22. return executor;
  23. }
  24. @Override
  25. @Bean("testExecutor")
  26. public Executor getAsyncExecutor() {
  27. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  28. //配置核心线程数
  29. executor.setCorePoolSize(8);
  30. //配置最大线程数
  31. executor.setMaxPoolSize(16);
  32. //配置队列大小
  33. executor.setQueueCapacity(64);
  34. //配置线程池中的线程的名称前缀
  35. executor.setThreadNamePrefix("async-service-");
  36. // 设置拒绝策略:当pool已经达到max size的时候,如何处理新任务
  37. // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
  38. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  39. //执行初始化
  40. executor.initialize();
  41. return executor;
  42. }
  43. @Override
  44. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  45. return new AsyncExceptionHandler();
  46. }
  47. }