package com.changshin.threadpool;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ThreadPool {
/**
* 连接池
*/
private ExecutorService pool;
@PostConstruct
public void afterPropertiesSet() {
pool = Executors.newFixedThreadPool(50);
}
public List<OtherServerResponse> test(List testList) {
List<Future<OtherServerResponse>> futureList = new ArrayList<Future<OtherServerResponse>>();
int tolSize = testList.size();
CountDownLatch countDownLatch = new CountDownLatch(10);//计数器
for (int i = 0; i < tolSize; i++) {
long num = (tolSize - countDownLatch.getCount()) * 50L;
futureList.add(pool.submit(() -> {
Thread.sleep(num);//对线程进行睡眠避免对调用服务造成压力
OtherServerResponse response = new OtherServerResponse();//模拟对其他接口调用,返回信息
System.out.println("执行对其他微服务接口调用");
return response;
}));
}
long rpcTimeout = 60L;//设置超时时间
List<OtherServerResponse> newList = new ArrayList<OtherServerResponse>();
for (Future<OtherServerResponse> future : futureList) {
try {
OtherServerResponse bean = future.get(rpcTimeout, TimeUnit.SECONDS);
newList.add(bean);
} catch (Throwable e) {
System.out.println("调用rpc异常");
throw new RuntimeException("调用rp异常");
}
}
return newList;
}
}
最近接到一个任务需要查询一个一个客户的交易列表,但是交易列表查询回来后,返回的字段不满足要求,需要根据列表子对象的id调用一个接口查询接口的详细信息。如果数据量大影响导致返回的速度。这里启用线程查询,节省了时间。