spring boot 使用TaskExecutor实现异步任务

1.新增配置类,开启异步任务支持

@Configuration //声明配置类
@EnableAsync //开启异步任务支持
public class TaskExecutorConfig implements AsyncConfigurer {

     @Override
      public Executor getAsyncExecutor() {
              ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
              taskExecutor.setCorePoolSize(5);//线程池大小
              taskExecutor.setMaxPoolSize(10);//线程池最大线程数
              taskExecutor.setQueueCapacity(25);//最大等待任务数
              taskExecutor.initialize();
              return taskExecutor;
      }

     @Override
      public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
              return null;
      }
}

2.通过@Async注解声明异步任务

@Service("asyncTaskService")
public class AsyncTaskService{    
     @Async
     public void excuteAsyncTaskTest(String name) {
          for(int i = 0;i < 100;i++) {
              System.out.println("正在执行异步任务"+name+i);
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              }
          }
     }
}

你可能感兴趣的:(spring,boot)