1. 程式人生 > >spring boot 使用TaskExecutor實現非同步任務

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();
              }
          }
     }
}