Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我们是否应该为每个异步请求运行goroutine,即使它们是从彼此派生的?_Go_Goroutine - Fatal编程技术网

我们是否应该为每个异步请求运行goroutine,即使它们是从彼此派生的?

我们是否应该为每个异步请求运行goroutine,即使它们是从彼此派生的?,go,goroutine,Go,Goroutine,我正在用go开发一个web应用程序,我知道在http包中,每个请求都在一个单独的goroutine中运行。现在,如果这个goroutine中的代码查询一个数据库,然后等待并使用db result调用一个远程api来获取一些相关数据等等,那么我应该在单独的goroutine中运行这些调用,还是http提供的调用就够了?这取决于您正在做什么 每个HTTP请求都应该按顺序处理。也就是说,您不应该为处理请求本身而启动goroutine: func myHandler(w http.ResponseWri

我正在用go开发一个web应用程序,我知道在http包中,每个请求都在一个单独的goroutine中运行。现在,如果这个goroutine中的代码查询一个数据库,然后等待并使用db result调用一个远程api来获取一些相关数据等等,那么我应该在单独的goroutine中运行这些调用,还是http提供的调用就够了?

这取决于您正在做什么

每个HTTP请求都应该按顺序处理。也就是说,您不应该为处理请求本身而启动goroutine:

func myHandler(w http.ResponseWriter, r *http.Request) {
    go func(w http.ResponseWriter, r *http.Request) {
        // There's no advantage to this
    }(w,r)
}
然而,在处理HTTP响应时,goroutine仍然有意义。最常见的两种情况可能是:

  • 你想同时做一些事情

    func myHandler(w http.ResponseWriter, r *http.Request) {
        wg := &sync.WaitGroup{}
        wg.Add(2)
        go func() {
            defer wg.Done()
            /* query a remote API */
        }()
        go func() {
            defer wg.Done()
            /* query a database */
        }()
        wg.Wait()
        // finish handling the response
    }
    
  • 您希望在响应HTTP请求后完成处理,这样web客户端就不必等待

    func myHandler(w http.ResponseWriter, r *http.Request) {
        // handle request
        w.Write( ... )
        go func() {
            // Log the request, and send an email
        }()
    }
    

  • 郊游很便宜。为您希望并行运行的内容创建单独的goroutine,否则将其设置为顺序。http提供的一个示例引用不足,似乎为了使用上下文功能,我们应该在单独的goroutine中运行对db等的每个调用。@JavadM.Amiri:使用上下文可能是在goroutine中运行内容的另一个原因,但我不知道为什么每个查询都需要一个单独的goroutine。