springboot 使用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();

              }

          }

     }

}

--------------------- 

作者:reader_writer 

来源:CSDN 

原文:https://blog.csdn.net/reader_writer/article/details/79656028 

版权声明:本文为博主原创文章,转载请附上博文链接!

Author:

发表评论

电子邮件地址不会被公开。 必填项已用*标注