AsyncConfiguration.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package cc.uncarbon.config;
  2. import java.util.concurrent.Executor;
  3. import java.util.concurrent.ThreadPoolExecutor;
  4. import lombok.RequiredArgsConstructor;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
  7. import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.scheduling.annotation.AsyncConfigurer;
  11. import org.springframework.scheduling.annotation.EnableAsync;
  12. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  13. /**
  14. * @author Uncarbon
  15. */
  16. @Slf4j
  17. @EnableAsync
  18. @Configuration
  19. @RequiredArgsConstructor
  20. public class AsyncConfiguration implements AsyncConfigurer {
  21. private final TaskExecutionProperties taskExecutionProperties;
  22. @Bean(name = "taskExecutor")
  23. public ThreadPoolTaskExecutor taskExecutor() {
  24. final String threadNamePrefix = "taskExecutor-";
  25. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  26. // 核心线程池大小 or 10
  27. executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize());
  28. // 最大线程数 or 50
  29. executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize());
  30. // 队列容量 or 10
  31. executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity());
  32. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  33. // 线程名前缀
  34. executor.setThreadNamePrefix(threadNamePrefix);
  35. // 这个配置是为了graceful shutdown?
  36. executor.setWaitForTasksToCompleteOnShutdown(true);
  37. executor.initialize();
  38. return executor;
  39. }
  40. @Override
  41. public Executor getAsyncExecutor() {
  42. log.debug("Creating Default Async Task Executor");
  43. return this.taskExecutor();
  44. }
  45. @Override
  46. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  47. return (ex, method, params) -> {
  48. log.error("执行异步任务'{}'出错", method);
  49. ex.printStackTrace();
  50. };
  51. }
  52. }