golang實現(xiàn)多協(xié)程下載文件(支持斷點續(xù)傳)
更新時間:2021年11月11日 10:01:44 作者:山與路
本文主要介紹了golang實現(xiàn)多協(xié)程下載文件,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
引言
寫這篇文章主要是周末休息太無聊,看了看別人代碼,發(fā)現(xiàn)基本上要么是多協(xié)程下載文件要么就只有單協(xié)程的斷點續(xù)傳,所以就試了試有進度條的多協(xié)程下載文件(支持斷點續(xù)傳)
package main
import (
"fmt"
"io"
"os"
"regexp"
"strconv"
"sync"
"github.com/qianlnk/pgbar"
)
/**
* 需求:
1. 多協(xié)程下載文件
2.斷點續(xù)連
**/
func main() {
//獲取要下載文件
DownloadFileName := "./123.zip"
//copy的文件
copyFileName := "./test.zip"
storgeFileName := "./current.txt"
//打開文件
sfile, err := os.Open(DownloadFileName)
if err != nil {
panic(err)
}
defer sfile.Close()
//獲取文件大小
info, _ := sfile.Stat()
downloadSize := info.Size()
var scount int64 = 1
if downloadSize%5 == 0 {
scount *= 5
} else {
scount *= 10
}
//分給每個協(xié)程的大小
si := downloadSize / scount
fmt.Printf("文件總大?。?v, 分片數(shù):%v,每個分片大?。?v\n", downloadSize, scount, si)
//open copy file
copyFile, err := os.OpenFile(copyFileName, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
panic(err)
}
storgeFile, err := os.OpenFile(storgeFileName, os.O_CREATE|os.O_RDWR, os.ModePerm)
if err != nil {
panic(err)
}
defer copyFile.Close()
var currentIndex int64 = 0
wg := sync.WaitGroup{}
fmt.Println("協(xié)程進度條")
pgb := pgbar.New("")
for ; currentIndex < scount; currentIndex++ {
wg.Add(1)
go func(current int64) {
p := pgb.NewBar(fmt.Sprint((current+1))+"st", int(si))
// p.SetSpeedSection(900, 100)
b := make([]byte, 1024)
bs := make([]byte, 16)
currentIndex, _ := storgeFile.ReadAt(bs, current*16)
//取出所有整數(shù)
reg := regexp.MustCompile(`\d+`)
countStr := reg.FindString(string(bs[:currentIndex]))
total, _ := strconv.ParseInt(countStr, 10, 0)
progressBar := 1
for {
if total >= si {
wg.Done()
break
}
//從指定位置開始讀
n, err := sfile.ReadAt(b, current*si+total)
if err == io.EOF {
wg.Done()
break
}
//從指定位置開始寫
copyFile.WriteAt(b, current*si+total)
storgeFile.WriteAt([]byte(strconv.FormatInt(total, 10)+" "), current*16)
total += int64(n)
if total >= si/10*int64(progressBar) {
progressBar += 1
p.Add(int(si / 10))
}
}
}(currentIndex)
}
wg.Wait()
storgeFile.Close()
os.Remove(storgeFileName)
fmt.Println("下載完成")
}
到此這篇關(guān)于golang實現(xiàn)多協(xié)程下載文件(支持斷點續(xù)傳)的文章就介紹到這了,更多相關(guān)golang 多協(xié)程下載文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go使用TimerController解決timer過多的問題
多路復用,實際上Go底層也是一種多路復用的思想去實現(xiàn)的timer,但是它是底層的timer,我們需要解決的問題就過多的timer問題!本文給大家介紹了Go使用TimerController解決timer過多的問題,需要的朋友可以參考下2024-12-12
Go語言反射reflect.Value實現(xiàn)方法的調(diào)用
本文主要介紹了Go語言反射reflect.Value實現(xiàn)方法的調(diào)用,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05
golang高并發(fā)系統(tǒng)限流策略漏桶和令牌桶算法源碼剖析
這篇文章主要介紹了golang高并發(fā)系統(tǒng)限流策略漏桶和令牌桶算法源碼剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06

