Java如何调用并行传递分块数据的方法
我有一个 API 调用一次只能接受 5 个子请求。因此,如果传入的子请求超过 10 个,我需要进行分块,然后根据 SLA 并行发送它们。
下面是一个非并行分块代码,我希望并行化此调用 invokeService(bulkRequestChunk)
int BULK_SUBREQUEST_SIZE = 5;
// infoRequestList size = 7
for (int i = 0; i < numOfSubRequests; i += BULK_SUBREQUEST_SIZE) {
List<InfoRequest> infoRequestChunk;
if (i + BULK_SUBREQUEST_SIZE >= numOfSubRequests) {
infoRequestChunk = infoRequestList.subList(i, numOfSubRequests);
} else {
infoRequestChunk = infoRequestList.subList(i, i + BULK_SUBREQUEST_SIZE);
}
BulkRequest bulkRequestChunk = new BulkRequest();
bulkRequestChunk.setRequests(infoRequestChunk);
BulkResponse bulkResponseChunk = invokeService(bulkRequestChunk);
// output list to capture all chunked requests
bulkResponseList.add(bulkResponseChunk);
}
I have an API call that can only accept 5 subrequests at a time. So I need to chunkify if more than 10 subrequests come in and then send them in parallel as per the SLA.
Below is a nonparallel chunkified code and I am looking to parallelize this call invokeService(bulkRequestChunk)
int BULK_SUBREQUEST_SIZE = 5;
// infoRequestList size = 7
for (int i = 0; i < numOfSubRequests; i += BULK_SUBREQUEST_SIZE) {
List<InfoRequest> infoRequestChunk;
if (i + BULK_SUBREQUEST_SIZE >= numOfSubRequests) {
infoRequestChunk = infoRequestList.subList(i, numOfSubRequests);
} else {
infoRequestChunk = infoRequestList.subList(i, i + BULK_SUBREQUEST_SIZE);
}
BulkRequest bulkRequestChunk = new BulkRequest();
bulkRequestChunk.setRequests(infoRequestChunk);
BulkResponse bulkResponseChunk = invokeService(bulkRequestChunk);
// output list to capture all chunked requests
bulkResponseList.add(bulkResponseChunk);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 ExecutorService 并提交任务以并行运行:
Use an ExecutorService and submit it tasks to run in parallel: