gpt4 book ai didi

java - 在 Java 中为 HTTP 调用处理大文件

转载 作者:可可西里 更新时间:2023-11-01 16:52:20 26 4
gpt4 key购买 nike

我有一个包含数百万行的文件需要处理。文件的每一行都会产生一个 HTTP 调用。我正在尝试找出解决问题的最佳方法。

我显然可以只读取文件并按顺序进行调用,但速度会非常慢。我想并行调用,但我不确定是否应该将整个文件读入内存(我不太喜欢)或者尝试并行读取文件(我'我不确定是否有意义)。

只是在这里寻找一些关于解决问题的最佳方法的想法。如果有一个现有的框架或库可以做类似的事情,我也很乐意使用它。

谢谢。

最佳答案

I'd like to parallelize the calls, but I'm not sure if I should read the entire file into memory

您应该使用一个带有有界 BlockingQueueExecutorService。当您读入百万行时,您将作业提交到线程池,直到 BlockingQueue 已满。通过这种方式,您将能够同时运行 100 个(或任何最佳数量)HTTP 请求,而无需事先读取文件的所有行。

您需要设置一个 RejectedExecutionHandler,如果队列已满则阻塞。这比调用者运行处理程序要好。

BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(100);
// NOTE: you want the min and max thread numbers here to be the same value
ThreadPoolExecutor threadPool =
new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, queue);
// we need our RejectedExecutionHandler to block if the queue is full
threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
// this will block the producer until there's room in the queue
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException(
"Unexpected InterruptedException", e);
}
}
});

// now read in the urls
while ((String url = urlReader.readLine()) != null) {
// submit them to the thread-pool. this may block.
threadPool.submit(new DownloadUrlRunnable(url));
}
// after we submit we have to shutdown the pool
threadPool.shutdown();
// wait for them to complete
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

...
private class DownloadUrlRunnable implements Runnable {
private final String url;
public DownloadUrlRunnable(String url) {
this.url = url;
}
public void run() {
// download the URL
}
}

关于java - 在 Java 中为 HTTP 调用处理大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13184005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com