一、yml配置
#多线程配置 mythreadpool: maxPoolSize: 20 corePoolSize: 8 queueCapacity: 2048 keepAliveSeconds: 60 threadNamePrefix: springThreadPool waitForTasksToCompleteOnShutdown: true
二、配置类
@Configuration
@EnableAsync
public class MyThreadPoolConfig {
@Bean("myThreadPool")
public Executor threadPoolExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数:线程池创建时候初始化的线程数
executor.setCorePoolSize(10);
// 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
executor.setMaxPoolSize(20);
// 缓冲队列:用来缓冲执行任务的队列
executor.setQueueCapacity(500);
// 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(60);
// 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
executor.setThreadNamePrefix("do-ocr-");
// 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程)
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
executor.initialize();
return executor;
}
}
三、专门写一个异步线程执行的spring组件类
@Component
public class AsyncRequestComponent {
@Autowired
MongoTemplate mongoTemplate;
@Async("myThreadPool")
public CompletableFuture mockHttpRequest(String imageUrl){
String threadName = Thread.currentThread().getName();
System.out.println("线程" + threadName + "开始调用,输出:" + imageUrl);
String result = "";
Test test = new Test();
try {
result = XxxUtil.requestUrl(imageUrl);
JSONObject jsonObject = JSONObject.parseObject(result);
JSONObject invoiceJsonObject = mongoTemplate.insert(jsonObject);
test = t.setName("测试");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("线程" + threadName + "调用结束,输出:" + imageUrl);
return CompletableFuture.completedFuture(test);
}
}
四、controller层
@ApiOperation("测试")
@RequestMapping("/test")
public R test(@RequestBody TestDto testDto){
List> listOfFuture = new ArrayList<>();
List testDto =new ArrayList();
for (int i =0;i
CompletableFuture completableFuture = asyncOcr.mockHttpRequest(disImages.getImgs()[i]);
listOfFuture.add(completableFuture);
}
//必须想办法阻塞,直到所有线程返回结果了
CompletableFuture result = CompletableFuture.allOf(listOfFuture.toArray(new CompletableFuture[listOfFuture.size()]));
CompletableFuture> listCompletableFuture = result.thenApply(v ->
listOfFuture.stream().map(CompletableFuture::join).collect(Collectors.toList()));
try {
testDto = listCompletableFuture.get();
logger.info(testDto.toString());
}catch (Exception e){
e.printStackTrace();
}
return R.ok(testDto);
}
相关注解和方法
@EnableAsync
@Async(“myThreadPool”)
CompletableFuture
CompletableFuture.allOf()
CompletableFuture.get()
Thread.currentThread().getName() 获得当前线程名字



