这样一个场景,需要java后端调外部接口,如果是只有几十次调用的话访问速度还是较快的,但是现在一次性调用的数据量大概有1K-4K左右,需要类似多线程调用接口
在网上找来的一个方法,出处找不太到了,这里记录一下
// 用于下面的具体方法处理
@Autowired
private IService service;
//分批处理的配置类
@Autowired
private ThreadConfig threadConfig;
// xxxList就是需要分多段处理的List, 50是分段后每一个List的长度
List<List<PersonEduInfoDto>> allList = Lists.partition(xxxList, 50);
int batchNum = allList.size();
Executor threadConfigExecutor = threadConfig.getExecutor();
List<CompletableFuture> results = new ArrayList<>();
for (List<PersonEduInfoDto> xxxListList :allList){
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 处理方法
service.fun1(xxxListList);
return "";
}, threadConfigExecutor);
results.add(future);
}
// 等待数据处理完成并合并
CompletableFuture.allOf(results.toArray(results.toArray(new CompletableFuture[batchNum]))).join();
ThreadConfig配置类
package com.zjsos.onlineworker.config;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class ThreadConfig {
/**
* 执行需要依赖线程池,这里就来配置一个线程池
* @return
*/
// 当池子大小小于corePoolSize,就新建线程,并处理请求
// 当池子大小等于corePoolSize,把请求放入workQueue(QueueCapacity)中,池子里的空闲线程就去workQueue中取任务并处理
// 当workQueue放不下任务时,就新建线程入池,并处理请求,如果池子大小撑到了maximumPoolSize,就用RejectedExecutionHandler来做拒绝处理
// 当池子的线程数大于corePoolSize时,多余的线程会等待keepAliveTime长时间,如果无请求可处理就自行销毁
@Bean("MyExecutor")
public Executor getExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//设置核心线程数
executor.setCorePoolSize(10);
//设置最大线程数
executor.setMaxPoolSize(100);
//线程池所使用的缓冲队列
executor.setQueueCapacity(250);
//设置线程名
executor.setThreadNamePrefix("JcTest-Async");
//设置多余线程等待的时间,单位:秒
//executor.setKeepAliveSeconds();
// 初始化线程
executor.initialize();
return executor;
}
}
application.yml配置文件
async:
executor:
thread:
# 配置核心线程数
core_pool_size: 10
# 配置最大线程数
max_pool_size: 20
# 配置队列大小
queue_capacity: 999
name:
prefix: async-service-