golang/python 下載大檔案時怎樣避免oom

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

    問題情境:高頻系統中,agent 會向ATS 伺服器發出重新整理和預緩衝的請求,這裡的請求head 裡面有GET ,PURGE等,因為一般的預緩衝都是小檔案,但是某天,突然伺服器oom。。。罪魁禍首發現是並發GET 大檔案將伺服器打死了。第一個版本是python 的,第二個版本是golang 實現的, 這裡記錄下兩種語言的 下載大檔案的實現方式。

    第一種是python,使用的是request 庫, 使用流式讀取的方式,寫到空裝置中去。

    

res = self.session.request(method, url, data=body, headers=header, timeout=timeout, proxies=proxies, stream=True)with open("/dev/null", 'wb') as f:            for chunk in res.iter_content(chunk_size=1024):                if chunk: # filter out keep-alive new chunks                    f.write(chunk)                    f.flush()

    第二種方式,對於golang ,使用io.Copy(), 將response copy 到空裝置中。

func downLoadFile(url string)(len int, err error){//err write /dev/null: bad file descriptor#out, err := os.OpenFile("/dev/null", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)defer out.Close()resp, err := http.Get(url)defer resp.Body.Close()n, err := io.Copy(out, resp.Body)return n, err}

    使用這種方式為什麼不會出現oom 的情況?因為兩個原因,第一個, resp.Body 只是個reader 並沒有發生真實的讀取操作,第二個是io.copy 這個函數設定了緩衝區大小限制為3m,不會一次全部讀取到記憶體中,下面是標準庫的源碼:

    

func Copy(dst Writer, src Reader) (written int64, err error) {return copyBuffer(dst, src, nil)}// copyBuffer is the actual implementation of Copy and CopyBuffer.// if buf is nil, one is allocated.func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) {// If the reader has a WriteTo method, use it to do the copy.// Avoids an allocation and a copy.if wt, ok := src.(WriterTo); ok {return wt.WriteTo(dst)}// Similarly, if the writer has a ReadFrom method, use it to do the copy.if rt, ok := dst.(ReaderFrom); ok {return rt.ReadFrom(src)}if buf == nil {buf = make([]byte, 32*1024) //這一步可以控制每次緩衝區迭代的大小,預設大小是3m}for {nr, er := src.Read(buf)if nr > 0 {nw, ew := dst.Write(buf[0:nr])if nw > 0 {written += int64(nw)}if ew != nil {err = ewbreak}if nr != nw {err = ErrShortWritebreak}}if er != nil {if er != EOF {err = er}break}}return written, err}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.