io.Copy在golang中导致内存不足 [英] io.Copy cause out of memory in golang

查看:2327
本文介绍了io.Copy在golang中导致内存不足的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用io.Copy()复制一个大约700Mb的文件,但它会导致内存不足

  bodyBuf: =&; bytes.Buffer {} 
bodyWriter:= multipart.NewWriter(bodyBuf)

//关键步骤
fileWriter,err:= bodyWriter.CreateFormFile(paramName,fileName)
if err!= nil {
return nil,err
}

file,err:= os.Open(fileName)//文件大小约为700Mb
if err!= nil {
return nil,err
}
推迟file.Close()

// iocopy
copyLen, err:= io.Copy(fileWriter,file)//这会导致内存不足
if err!= nil {
fmt.Println(io.copy():,err)

return nil,err
}

错误信息如下:

 运行时:由OS分配的内存(0x752cf000)不在可用范围内[0x18700000,0x98700000)
运行时:内存不足:无法分配1080229888字节块(1081212928使用中)
致命错误:内存不足

我为buf分配了足够的内存,导致bodyWriter.CreateFormFile()中的内存不足,导致内存不足,导致内存不足。

$ p $ buf := make([] byte,766509056)
bodyBuf:= bytes.NewBuffer(buf)
bodyWriter:= multipart.NewWriter(bodyBuf)
$ b $ fileWriter,err:= bodyWriter .CreateFormFile(paramName,fileName)//内存不足
if err!= nil {
return nil,err
}

解决方案

这是因为您正在'复制'到 bodyBuf ,这是一个内存缓冲区,强制Go尝试分配一块与整个文件一样大的内存块。



根据您使用 multipart 它看起来像你试图通过HTTP流式传输文件?在这种情况下,请不要将 bytes.Buffer 传递给 multipart.NewWriter ,而是直接传递您的http连接。

I use io.Copy() to copy a file, about 700Mb, but it cause out of memory

bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)

//key step
fileWriter, err := bodyWriter.CreateFormFile(paramName, fileName)
if err != nil {
    return nil, err
}

file, err := os.Open(fileName) //the file size is about 700Mb
if err != nil {
    return nil, err
}
defer file.Close()

//iocopy
copyLen, err := io.Copy(fileWriter, file) // this cause out of memory
if err != nil {
    fmt.Println("io.copy(): ", err)

    return nil, err
}

The error message as follow:

runtime: memory allocated by OS (0x752cf000) not in usable range [0x18700000,0x98700000)
runtime: out of memory: cannot allocate 1080229888-byte block (1081212928 in use)
fatal error: out of memory

I allocate enough memory for buf, it cause out of memory in bodyWriter.CreateFormFile()

buf := make([]byte, 766509056)
bodyBuf := bytes.NewBuffer(buf)
bodyWriter := multipart.NewWriter(bodyBuf)

fileWriter, err := bodyWriter.CreateFormFile(paramName, fileName) // out of memory
if err != nil {
    return nil, err
}

解决方案

That's because you are 'copying', to bodyBuf, which is an in-memory buffer, forcing Go to try an allocate a block of memory as big as the entire file.

Based on your use of multipart it looks like you are trying to stream the file over http? In that case, don't pass a bytes.Buffer to multipart.NewWriter, directly pass your http connection instead.

这篇关于io.Copy在golang中导致内存不足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆