我同時從配置對象切片(其中每個配置對象包含需要下載的 URL)下載文件(使用 WaitGroup),但是當我使用并發時,我會在每次執行時獲得完全相同的數據。我相信我將下面的所有內容都包含在一個最小的可重復示例中。這是我的進口:package mainimport ( "encoding/json" "fmt" "io" "io/ioutil" "log" "net/http" "os" "path" "path/filepath" "strconv" "strings" "sync")循環遍歷我的對象并執行 go 例程來下載每個文件的方法如下:func downloadAllFiles(configs []Config) { var wg sync.WaitGroup for i, config := range configs { wg.Add(1) go config.downloadFile(&wg) } wg.Wait()}基本上,我的功能是將文件從 URL 下載到 NFS 上存儲的目錄中。這是下載功能:func (config *Config) downloadFile(wg *sync.WaitGroup) { resp, _ := http.Get(config.ArtifactPathOrUrl) fmt.Println("Downloading file: " + config.ArtifactPathOrUrl) fmt.Println(" to location: " + config.getNfsFullFileSystemPath()) defer resp.Body.Close() nfsDirectoryPath := config.getBaseNFSFileSystemPath() os.MkdirAll(nfsDirectoryPath, os.ModePerm) fullFilePath := config.getNfsFullFileSystemPath() out, err := os.Create(fullFilePath) if err != nil { panic(err) } defer out.Close() io.Copy(out, resp.Body) wg.Done()}這是 Config 結構的最小部分:type Config struct { Namespace string `json:"namespace,omitempty"` Tenant string `json:"tenant,omitempty"` Name string `json:"name,omitempty"` ArtifactPathOrUrl string `json:"artifactPathOrUrl,omitempty"`}以下是實例/輔助函數:func (config *Config) getDefaultNfsURLBase() string { return "http://example.domain.nfs.location.com/"}func (config *Config) getDefaultNfsFilesystemBase() string { return "/data/nfs/location/"}func (config *Config) getBaseNFSFileSystemPath() string { basePath := filepath.Dir(config.getNfsFullFileSystemPath()) return basePath}
同時多次下載同一文件
慕桂英4014372
2023-07-17 17:49:01