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

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制