public class ThreadPoolDemo2 {

LinkedBlockingDeque<Request> queue = new LinkedBlockingDeque<>();//阻塞队列 秉承先进先出原则

@PostConstruct //启动和接口没关系,只和项目启动有关系
public void doBusniss() {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
int size = queue.size();
if(size == 0){
return ; //没有任务不执行
}

List<Map<String,String>> params = new ArrayList<>();//批量调用的时候的请求参数
List<Request> requests = new ArrayList<>();//对接口响应对应

for (int i = 0; i < size; i++) {//队列中的所有元素
Request request = queue.poll(); //把队列中的所有元素拿出来
Map<String,String> map = new HashMap<>();
map.put("no",request.no);
map.put("orderId",request.orderId);
params.add(map);
requests.add(request);
}

//批量处理params
System.out.println(params+"批量处理");
List<Map<String,Object>> response = new ArrayList<>(); //返回的批量的结果

for (Request request : requests) { //匹配结果 用算法和数据结构优化
String no = request.no;
for (Map<String, Object> map : response) {
if(no.equals(map.get("no").toString())){
request.future.complete(map); //将对应的结果放进对应的CompletableFuture
break;
}
}
}
}
},100,10, TimeUnit.MILLISECONDS);//定时线程任务 每10毫秒执行一次 100为启动延迟100ms
}


//将所有请求都放入阻塞队列中
public Map<String,Object> queryOrderBatch(String orderId)throws Exception{
String no = UUID.randomUUID().toString();
CompletableFuture<Map<String,Object>> future = new CompletableFuture<>();
Request request = new Request();
request.no = no;
request.orderId = orderId;
request.future = future;
queue.add(request);
return future.get(); //阻塞,拿不到数据不返回
}
}

class Request {
String no;
String orderId;
CompletableFuture<Map<String,Object>> future;
}
posted on 2022-08-04 22:12  我叫福禄娃  阅读(118)  评论(0编辑  收藏  举报