spring学习--9 多任务
程序员文章站
2022-05-27 09:43:51
...
spring采用TaskExecutor完成多任务处理工作和并发编程,可以使用TheadPoolTaskExecutor创建一个基于线程池的TaskExecutor。如下例所示。
1、Configuration类
package com.taskexecutor;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@ComponentScan("com.taskexecutor")
// 注解与接口AsyncConfigurer或AsyncConfigurerSupport配合使用,形成支持异步的配置
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
// 创建基于线程池的任务执行器,该任务执行器的参数需要进行合理设置。
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(60);
taskExecutor.setMaxPoolSize(100);
taskExecutor.setQueueCapacity(2500);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
2. 任务类(相当于Java中的Runnable 类或Thread 类)
package com.taskexecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {
@Async //
public void executeAsyncTask(Integer i) {
System.out.println("执行异步任务:" + i);
}
@Async
public void executeAsyncTaskPlus(Integer i) {
System.out.println("执行异步任务+1: " + (++i));
}
}
3.测试类
package com.taskexecutor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Bootrap {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
AsyncTaskService taskService = context.getBean(AsyncTaskService.class);
for (int i = 0; i < 100; i++) {
// 每个execute方法代表一个并行的异步任务
taskService.executeAsyncTask(i);
taskService.executeAsyncTaskPlus(i);
}
context.close();
}
}