AsyncConfig.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package cn.efunbox.base.configuration;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.core.task.SimpleAsyncTaskExecutor;
  9. import org.springframework.scheduling.annotation.AsyncConfigurer;
  10. import org.springframework.scheduling.annotation.EnableAsync;
  11. import java.lang.reflect.Method;
  12. import java.util.concurrent.Executor;
  13. import java.util.concurrent.ExecutorService;
  14. import java.util.concurrent.Executors;
  15. import java.util.concurrent.ScheduledExecutorService;
  16. @Configuration
  17. @EnableAsync()
  18. public class AsyncConfig implements AsyncConfigurer {
  19. private Logger logger = LoggerFactory.getLogger(getClass());
  20. @Value("${schedule.threadPoolAsyncTaskExecutor.thread.size}")
  21. private Integer threadSize;
  22. /**
  23. * name = threadPoolAsyncTaskExecutor 时
  24. * 使用基于线程池的 Task 执行器
  25. * @return
  26. */
  27. @Bean(name = "threadPoolAsyncTaskExecutor")
  28. public Executor threadPoolAsyncTaskExecutor() {
  29. ExecutorService executor = Executors.newFixedThreadPool(threadSize);
  30. return executor;
  31. }
  32. @Bean(name = "scheduledExecutorService")
  33. public ScheduledExecutorService threadPoolAsyncScheduleExecutor() {
  34. ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(threadSize);
  35. return scheduledExecutorService;
  36. }
  37. /**
  38. * 只有@Async 注解时
  39. * 使用 原生的 SimpleAsyncTaskExecutor 执行器
  40. * @return
  41. */
  42. @Override
  43. public Executor getAsyncExecutor() {
  44. return new SimpleAsyncTaskExecutor();
  45. }
  46. /**
  47. * 实现 异常处理 handler
  48. * @return
  49. */
  50. @Override
  51. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  52. return new CustomAsyncExceptionHandler();
  53. }
  54. class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
  55. @Override
  56. public void handleUncaughtException(final Throwable throwable, final Method method, final Object... obj) {
  57. logger.error("Exception message - " + throwable.getMessage());
  58. logger.error("Method name - " + method.getName());
  59. for (final Object param : obj) {
  60. logger.error("Param - " + param);
  61. }
  62. }
  63. }
  64. }