登录
首页 >  Golang >  Go问答

同时多次下载同一文件

来源:stackoverflow

时间:2024-04-09 09:00:34 334浏览 收藏

本篇文章给大家分享《同时多次下载同一文件》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我同时从配置对象切片(其中每个配置对象包含需要下载的 url)下载文件(使用 waitgroup),但是当我使用并发时,我会在每次执行时获得完全相同的数据。

我相信我包含了下面的所有内容作为一个最小的可重现示例。

这是我的导入:

package main

import (
    "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
}

func (config *config) getnfsfullfilesystempath() string {
    // basepath is like: /data/nfs/location/
    trimmedbasepath := strings.trimsuffix(config.getdefaultnfsfilesystembase(), "/")
    filename := config.getbasefilename()
    return trimmedbasepath + "/" + config.tenant + "/" + config.namespace + "/" + config.name + "/" + filename
}

以下是我获取配置并解组它们的方法:

func getconfigs() string {
    b, err := ioutil.readfile("pulsardeploy_example.json")
    if err != nil {
        fmt.print(err)
    }
    str := string(b) // convert content to a 'string'
    return str
}

func deserializejson(configjson string) []config {
    jsonasbytes := []byte(configjson)
    configs := make([]config, 0)
    err := json.unmarshal(jsonasbytes, &configs)
    if err != nil {
        panic(err)
    }
    return configs
}

作为一个最小的示例,我认为 pulsardeploy_example.json 文件的数据应该有效:

[{   "artifactPathOrUrl": "http://www.java2s.com/Code/JarDownload/sample/sample.jar.zip",
        "namespace": "exampleNamespace1",
        "name": "exampleName1",
        "tenant": "exampleTenant1"
      },

      {   
        "artifactPathOrUrl": "http://www.java2s.com/Code/JarDownload/sample-calculator/sample-calculator-bundle-2.0.jar.zip",
        "namespace": "exampleNamespace1",
        "name": "exampleName2",
        "tenant": "exampleTenant1"
      },
      {   
        "artifactPathOrUrl": "http://www.java2s.com/Code/JarDownload/helloworld/helloworld.jar.zip",
        "namespace": "exampleNamespace1",
        "name": "exampleName3",
        "tenant": "exampleTenant1"
      },
      {   
        "artifactPathOrUrl": "http://www.java2s.com/Code/JarDownload/fabric-activemq/fabric-activemq-demo-7.0.2.fuse-097.jar.zip",
        "namespace": "exampleNamespace1",
        "name": "exampleName4",
        "tenant": "exampleTenant1"
      }
]

(请注意,示例文件 url 只是我在网上抓取的随机 jars。)

当我运行我的代码时,它不是下载每个文件,而是重复下载相同的文件,并且它打印到控制台的信息(从 downloading file:to location: 行)对于每个文件完全相同对象(而不是打印每个对象唯一的消息),这绝对是一个并发问题。

这个问题让我想起如果您尝试运行带有闭包的 for loop 并最终将单个对象实例锁定到循环中并在同一个对象上重复执行,会发生什么。

是什么导致了这种行为?如何解决?


解决方案


我很确定你的猜测

这个问题让我想起如果您尝试运行带有闭包的 for 循环并最终将单个对象实例锁定到循环中并在同一个对象上重复执行,会发生什么情况。

是正确的。简单的修复方法是“分配给本地变量”,例如

for _, config := range configs {
    wg.add(1)
    cur := config
    go cur.downloadfile(&wg)
}

但我不喜欢将 waitgroup 作为参数的 api,所以我建议

for _, config := range configs {
    wg.Add(1)
    go func(cur Config) {
       defer wg.Done()
       cur.downloadFile()
    }(config)
}

并将 downloadfile 签名更改为 func (config *config) downloadfile() 并删除其中的 wg 用法。

理论要掌握,实操不能落!以上关于《同时多次下载同一文件》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>