使用goroutines WaitingGroup时随机发生错误

Battal Ghazi:

我有一个包含两个goroutines的处理程序。前端每10秒执行一次处理程序。调用后,goroutines将GET http请求发送到外部API。由于某种原因,有时(不经常)我在任何goroutine中随机出现以下错误(似乎外部API拒绝了该请求)。

状态码:408

panic:读取tcp 192.168.1.106:62598->80.243.175.58:443:wsarecv:现有连接被远程主机强行关闭。goroutine 8280 [正在运行]:Monitoring / monitoring-v2-goAPI / services.GetNodeCpuLimits.func2(0x815ba0,0xc04231a1c0,0x0,0x0,0x0,0x0,0xc042158240,0x14,0x0,0x0,...)

当发生这种情况时,就会触发panic(err)并终止我的应用程序。由于我以异步方式重建处理程序以提高速度(在请求只是同步之前),因此发生了此错误。

我想知道我做错了什么。如果没有,我该如何处理?我无法负担终止申请的费用。

   func TestFunc(w http.ResponseWriter, r *http.Request) {

        c := make(chan NgxJSON)
        wg := &sync.WaitGroup{}

        var queryParams QueryParams
        _ = json.NewDecoder(r.Body).Decode(&queryParams)
        fmt.Println("- queryParams ->", queryParams)

        wg.Add(1)
        go func(queryParams QueryParams, c chan NgxJSON, wg *sync.WaitGroup) {
            defer wg.Done()

            req, err := http.NewRequest("GET", APIURL1+queryParams.Param1, nil)


            if err != nil {
                fmt.Println(err)
                return
            }

            client := &http.Client{}
            resp, err := client.Do(req)
            if err != nil {
                panic(err)   //<-- Error triggers here!!
            }
            defer resp.Body.Close()


            body, _ := ioutil.ReadAll(resp.Body) 

            var response Response
            json.Unmarshal([]byte(string(body)), &response)


            //DO THINGS

            c <- ngxJSON

        }(queryParams, c, wg)

        wg.Add(1)
        go func(queryParams QueryParams, c chan NgxJSON, wg *sync.WaitGroup) {
            defer wg.Done()
            req, err := http.NewRequest("GET", APIURL2+APIURL2+queryParams.Param2, nil)

            if err != nil {
                fmt.Println(err) 
                return
            }

            client := &http.Client{}
            resp, err := client.Do(req)
            if err != nil {
                panic(err) //<-- Error triggers here!!
            }
            defer resp.Body.Close()



            body, _ := ioutil.ReadAll(resp.Body)

            var response Response
            json.Unmarshal([]byte(string(body)), &response)


           //DO THINGS

                c <- ngxJSON

            }

        }(queryParams, c, wg)

        go func() {
            wg.Wait()
            close(c)
        }()

    //DO THINGS



    }
沃尔克:

我无法负担终止申请的费用。

然后不要惊慌,而是要处理408,例如通过在上游重试或返回错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章