duanji7881 2017-04-29 07:02
浏览 125

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

I'm developing a web application in go and I know in http package, every request is run in a separate goroutine. Now, if the code inside this goroutine queries a database then wait and using db result calls a remote api to fetch some related data and son on and so forth, shall I run each of these calls in separate goroutine or the one provided by http is enough?

  • 写回答

1条回答 默认 最新

  • donvo24600 2017-04-29 10:49
    关注

    That depends on what you're doing.

    Each HTTP request should be handled sequentially. That is to say, you shouldn't fire off a goroutine for handling the request itself:

    func myHandler(w http.ResponseWriter, r *http.Request) {
        go func(w http.ResponseWriter, r *http.Request) {
            // There's no advantage to this
        }(w,r)
    }
    

    However, there are still times when goroutines make sense when handling an HTTP response. The two most common situations are probably:

    1. You want to do something in parallel.

      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. You want to finish handling something after responding to the HTTP request, so that the web client doesn't have to wait.

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

报告相同问题?