使用AsyncHttpClient下载文件时出现OutOfMemoryError

问题描述

我在异步下载约2k个文件(每个0.5MB)时发生OutOfMemoryError。 在我的本地计算机上,一切正常,但是在docker映像中这样做时,它缺少内存。我不想将docker映像的内存分配增加到本地计算机的大小(尽管如果这是我执行此操作的唯一可能的方法)。

要下载每个文件,我都使用这种方法

static void download(String fileUrl,File localFile) throws HttpException,CannotReadException,TagException,InvalidAudioFrameException,ExecutionException,InterruptedException,IOException {
    FileOutputStream stream = new FileOutputStream(localFile)
    AsyncHttpClient client = Dsl.asyncHttpClient()

    client.prepareGet(fileUrl)
            .execute(new AsyncCompletionHandler<FileOutputStream>() {

                @Override
                AsyncHandler.State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
                    def status = responseStatus.getStatusCode()
                    if (status != 200) {
                        println(status + " file not downloaded: " + fileUrl)
                        return State.ABORT
                    }
                    return State.CONTINUE
                }

                @Override
                AsyncHandler.State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                    stream.getChannel()
                            .write(bodyPart.getBodyByteBuffer())
                    return State.CONTINUE
                }

                @Override
                FileOutputStream onCompleted(Response response) throws Exception {
                    return stream
                }
            })
            .get()

    stream.getChannel().close()
    client.close()
}

在每个下载的文件上,我都会执行一些检查(也以异步方式进行检查)并收集结果。

List filesThatMatchMyTest = Flux.fromIterable(items)
            .parallel()
            .runOn(Schedulers.boundedElastic())
            .map { it ->
                def uri = it.URI
                File localFile = File.createTempFile("file-$uri",".txt")
                String fileUrl = createFileLink(uri)
                download(fileUrl,localFile)
                return check(localFile,locale,fileUrl)
            }
            .sequential()
            .filter { !it.isBlank() }
            .collectList()
            .block()

我正在寻找一种有助于在代码解决此问题的解决方案。

侧面说明,本地计算机具有16 GB的内存,而docker image 2 GB

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)