AsyncConfig.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package com.cec.plugins.config;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.scheduling.annotation.AsyncConfigurer;
  6. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  7. import java.lang.reflect.Method;
  8. import java.util.concurrent.Executor;
  9. import java.util.concurrent.ThreadPoolExecutor;
  10. /**
  11. * @author zhanghaijun
  12. * @date 2023/8/20 10:25
  13. * @description 异步执行配置信息
  14. */
  15. @Slf4j
  16. @Configuration
  17. public class AsyncConfig implements AsyncConfigurer {
  18. @Override
  19. public Executor getAsyncExecutor() {
  20. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  21. executor.setCorePoolSize(8); // 核心线程数
  22. executor.setMaxPoolSize(32); // 最大线程数
  23. executor.setQueueCapacity(30); // 队列大小
  24. executor.setKeepAliveSeconds(60); // 线程最大空闲时间
  25. // 指定用于新创建的线程名称的前缀。
  26. executor.setThreadNamePrefix("async-cec-");
  27. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  28. // 这一步千万不能忘了,否则报错: java.lang.IllegalStateException: ThreadPoolTaskExecutor not initialized
  29. executor.initialize();
  30. return executor;
  31. }
  32. /** 异步执行异常全局处理 */
  33. @Override
  34. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  35. return (Throwable ex, Method method, Object... params) -> {
  36. log.error("glob async exception: {},method: {}, params: {}", ex.getMessage(), method.getName(), params);
  37. };
  38. }
  39. }