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

时间:2017-04-29 07:02:48

标签: go goroutine

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

1 个答案:

答案 0 :(得分:1)

这取决于你正在做什么。

每个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仍然有意义。最常见的两种情况可能是:

  1. 您想要并行执行某些操作。

    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
    }
    
  2. 您希望在响应HTTP请求后完成的处理,以便Web客户端不必等待。

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