登录
首页 >  Golang >  Go问答

利用通道实现并发的POST API调用并将结果记录在文件中

来源:stackoverflow

时间:2024-03-14 21:03:29 377浏览 收藏

golang学习网今天将给大家带来《利用通道实现并发的POST API调用并将结果记录在文件中》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在尝试用 go 设计一个 http 客户端,它能够对 web 服务进行并发 api 调用,并在文本文件中写入一些数据。

func gettotalcalls() int {
    reader := bufio.newreader(os.stdin)
    ...
    return callint
}

gettotalcolls 决定我要拨打多少个电话,输入来自终端。

func writetofile(s string, nameprefix string) {
    filestore := fmt.sprintf("./data/%s_calls.log", nameprefix)
    ...
    defer f.close()
    if _, err := f.writestring(s); err != nil {
        log.println(err)
    }
}

writetofile 将从缓冲通道同步将数据写入文件。

func makerequest(url string, ch chan<- string, id int) {
    var jsonstr = []byte(`{"from": "saru", "message": "saru to discovery. over!"}`)
    req, err := http.newrequest("post", url, bytes.newbuffer(jsonstr))
    req.header.set("content-type", "application/json")
    client := &http.client{}
    start := time.now()
    resp, err := client.do(req)
    if err != nil {
        panic(err)
    }
    secs := time.since(start).seconds()
    defer resp.body.close()
    body, _ := ioutil.readall(resp.body)
    ch <- fmt.sprintf("%d, %.2f, %d, %s, %s\n", id, secs, len(body), url, body)
}

这是在 go routine 中进行 api 调用的函数。

最后这是 main 函数,它将数据从 go 例程发送到 bufferend 通道,稍后我遍历字符串的 bufferend 通道并将数据写入文件。

func main() {
    urlPrefix := os.Getenv("STARCOMM_GO")
    url := urlPrefix + "discovery"
    totalCalls := getTotalCalls()
    queue := make(chan string, totalCalls)

    for i := 1; i <= totalCalls; i++ {
        go makeRequest(url, queue, i)
    }

    for item := range queue {
        fmt.Println(item)
        writeToFile(item, fmt.Sprint(totalCalls))
    }
}

问题是在调用结束时,缓冲以某种方式阻塞,并且程序永远等待所有调用的结束。有人有更好的方法来设计这样的用例吗?我的最终目标是检查不同数量的并发发布请求,每个调用需要多少时间,以便对 5、10、50、100、500、1000 组并发调用的 api 端点进行基准标记。


解决方案


必须有东西 close(queue)。否则 range 队列 将阻塞。如果你想 range 队列 ,你必须确保在最终客户端完成后关闭此通道。

但是...甚至不清楚您是否需要 range 队列 ,因为您确切知道将获得多少结果 - 它是 totalcalls。您只需要循环多次从 queue 接收即可。

我相信您的用例与 Worker Pools example on gobyexample 类似,因此您可能需要检查一下。以下是该示例的代码:

// In this example we'll look at how to implement
// a _worker pool_ using goroutines and channels.

package main

import (
    "fmt"
    "time"
)

// Here's the worker, of which we'll run several
// concurrent instances. These workers will receive
// work on the `jobs` channel and send the corresponding
// results on `results`. We'll sleep a second per job to
// simulate an expensive task.
func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("worker", id, "started  job", j)
        time.Sleep(time.Second)
        fmt.Println("worker", id, "finished job", j)
        results <- j * 2
    }
}

func main() {

    // In order to use our pool of workers we need to send
    // them work and collect their results. We make 2
    // channels for this.
    const numJobs = 5
    jobs := make(chan int, numJobs)
    results := make(chan int, numJobs)

    // This starts up 3 workers, initially blocked
    // because there are no jobs yet.
    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    // Here we send 5 `jobs` and then `close` that
    // channel to indicate that's all the work we have.
    for j := 1; j <= numJobs; j++ {
        jobs <- j
    }
    close(jobs)

    // Finally we collect all the results of the work.
    // This also ensures that the worker goroutines have
    // finished. An alternative way to wait for multiple
    // goroutines is to use a [WaitGroup](waitgroups).
    for a := 1; a <= numJobs; a++ {
        <-results
    }
}

你的“worker”发出 http 请求,否则它的模式几乎相同。请注意最后的 for 循环,它从通道读取已知次数。

到这里,我们也就讲完了《利用通道实现并发的POST API调用并将结果记录在文件中》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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