三种SpringBoot中实现异步调用的方法总结

  @Configuration

  @EnableAsync

  public class AsyncConfig implements AsyncConfigurer {

  @Bean(name = "asyncExecutor")

  public TaskExecutor asyncExecutor() {

  ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

  executor.setCorePoolSize(10);

  executor.setMaxPoolSize(20);

  executor.setQueueCapacity(100);

  executor.setThreadNamePrefix("async-");

  executor.initialize();

  return executor;

  }

  @Override

  public Executor getAsyncExecutor() {

  return asyncExecutor();

  }

  @Override

  public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {

  return new SimpleAsyncUncaughtExceptionHandler();

  }

  }

  @Service

  public class AsyncService {

  @Autowired

  @Qualifier("asyncExecutor")

  private TaskExecutor taskExecutor;

  public void asyncTask() {

  taskExecutor.execute(() -> {

  // 异步任务执行的逻辑

  });

  }

  }