异步线程池

该版本重写了spring默认线程池,代码地址:

  1. eladmin-system -> me.zhengjie.config.AsyncTaskExecutePool

源码如下:

  1. @Slf4j
  2. @Configuration
  3. public class AsyncTaskExecutePool implements AsyncConfigurer {
  4. //注入配置类
  5. private final AsyncTaskProperties config;
  6. public AsyncTaskExecutePool(AsyncTaskProperties config) {
  7. this.config = config;
  8. }
  9. @Override
  10. public Executor getAsyncExecutor() {
  11. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  12. //核心线程池大小
  13. executor.setCorePoolSize(config.getCorePoolSize());
  14. //最大线程数
  15. executor.setMaxPoolSize(config.getMaxPoolSize());
  16. //队列容量
  17. executor.setQueueCapacity(config.getQueueCapacity());
  18. //活跃时间
  19. executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
  20. //线程名字前缀
  21. executor.setThreadNamePrefix("el-async-");
  22. // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
  23. // CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
  24. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  25. executor.initialize();
  26. return executor;
  27. }
  28. @Override
  29. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  30. return (throwable, method, objects) -> {
  31. log.error("===="+throwable.getMessage()+"====", throwable);
  32. log.error("exception method:"+method.getName());
  33. };
  34. }
  35. }

使用方式如下

  1. // 在 service 的方法上使用注解
  2. @Async