dty5753
2017-02-07 02:01
浏览 189
已采纳

Golang如何停止继续发出的Http请求

I was doing some load testing earlier today and found something peculiar, sometimes an Http request doesn't not die and keeps on firing . How can I correct that in my Golang code for instance see the image below . I am load testing loading 1,000 HTTP request but if you notice on the 1,000th request below it takes 392,999 milliseconds or 392 seconds while the rest of the request takes 2.2 seconds on average . I have done the test multiple times and sometimes it hangs . This is my code

func Home_streams(w http.ResponseWriter, r *http.Request) {
    var result string

    r.ParseForm()

    wg := sync.WaitGroup{}

    wg.Add(1)
    go func() {


    defer wg.Done()

    db.QueryRow("select json_build_object('Locations', array_to_json(array_agg(t))) from (SELECT latitudes,county,longitudes,"+
        "statelong,thirtylatmin,thirtylatmax,thirtylonmin,thirtylonmax,city"+
        " FROM zips where city='Orlando' ORDER BY city limit 5) t").Scan(&result)

    }()
    wg.Wait()

    fmt.Fprintf(w,result)
}

and I connect to the database with this code

func init() {
    var err error
    db, err = sql.Open("postgres","Postgres Connection String")

    if err != nil {
        log.Fatal("Invalid DB config:", err)
    }
    if err = db.Ping(); err != nil {
        log.Fatal("DB unreachable:", err)
    }
}

I would say that about 10 % of the time I load test this issue happens and the only way it stops is if I stop the requests manually otherwise it keeps on going indefinitely . I wonder if maybe this issue is addressed here https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779#.83uzpsp24 I am still learning my way around Golang . enter image description here

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtcmadj31951 2017-02-07 02:47
    已采纳

    and the only way it stops is if I stop the requests manually otherwise it keeps on going indefinitely

    You're not showing your full code, but it seems like you're using the http.ListenAndServe convenience function, which doesn't set a default timeout. So what I assume is happening is you're overloading your database server and your http server isn't set to timeout so it's just waiting for your database to respond.

    Assuming all of this is correct try doing something like this instead:

    srv := &http.Server{  
        ReadTimeout: 5 * time.Second,
        WriteTimeout: 10 * time.Second,
    }
    srv.ListenAndServe()
    

    There's a nice reference here.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题