gpt4 book ai didi

Golang http 连接无限期持续

转载 作者:IT王子 更新时间:2023-10-29 01:41:32 25 4
gpt4 key购买 nike

我有一个从数据库中检索数据的简单代码,我正在使用 Jmeter 对其执行负载测试。我正在做的是模拟 1,000 个请求,有时我会收到所有 1,000 个成功的请求,有时我会收到 999 个请求,我必须停止它,因为线程或最后的结果似乎会无限期地继续下去,这就是它的样子,请注意如何最后一次请求用了正常时间的 10 多倍。如果我不阻止它,那么该请求将一直持续下去。 enter image description here

这是我的代码

func get_data(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)
}

然后我有我的数据库连接

var db *sql.DB

func init() {
var err error
db, err = sql.Open("postgres", Postgres_Connect)
if err != nil {
log.Fatal("Invalid DB config:", err)
println("Invalid DB config:")
//log_errors("HomePage-Postgres: error opening database",err)
}
if err = db.Ping(); err != nil {
log.Fatal("DB unreachable:", err)
println()
}



}

这是我的 HTTP 服务器

func main() {

runtime.GOMAXPROCS(runtime.NumCPU())
r := mux.NewRouter()

r.HandleFunc("/mydata",Controllers.Get_Data)
http.Handle("/",r)


srv := &http.Server{
ReadTimeout: 20 * time.Second,
WriteTimeout: 20 * time.Second,
IdleTimeout: 120 * time.Second,
Addr: ":8000",
}
log.Println(srv.ListenAndServe())
}

我希望 ReadTimeOut 会终止连接,但它似乎没有

最佳答案

ReadTimeOut适用于 net/http 的服务器代码进行的读取,不适用于执行请求的 goroutine:

ReadTimeout is the maximum duration for reading the entire request, including the body.`

一旦请求被读取,这个值就不再被使用,处理程序负责决定事情是否超时。

如果你想在数据库查询完成之前取消 HTTP 请求,你可以使用 context.Context 来完成。 .

扩展req.Context , 添加一个 timeout or deadline , 将这个新上下文传递给 sql.QueryRowContext :

ctx, _ := context.WithTimeout( r.Context(), 20 * time.Second )

db.QueryRowContext(ctx, "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)

关于Golang http 连接无限期持续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44059263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com