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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题