最近一个 golang 写的 http.client 的,获取远程服务器数据,有时候会报错,尤其在数量很大的时候,老是收到 Connection reset by peer 这样的 提醒,都有点想用重试机制
百度,goolge 了一翻后,说的是 它会阻止连接被重用,可以有效的防止这个问题,也就是Http的短连接
1.在客户端关闭 http 连接
func main() { ???req, err := http.NewRequest("GET", "http://localhost",nil ) ???if err != nil { ???????log.Errorf("") ???} ???req.Close = true ???resp, err := http.Client.Do(req) ???...}
- 在头部设置连接状态为关闭
func main() { ???req, err := http.NewRequest("GET", "http://localhost",nil ) ???if err != nil { ???????log.Errorf("") ???} ???req.Header.Add("Connection", "close") ???resp, err := http.Client.Do(req) ???...}
- 使用
Transport
取消 HTTP利用连接func main() { ???tr := http.Transport{DisableKeepAlives: true} ???client := http.Client{Transport: &tr} ???resp, err := client.Get("https://golang.google.cn/") ???if resp != nil { ???????defer resp.Body.Close() ???} ???checkError(err) ???fmt.Println(resp.StatusCode) ???// 200 ???body, err := ioutil.ReadAll(resp.Body) ???checkError(err) ???fmt.Println(len(string(body)))}
服务器端设置短连接
func main(){ ???server := &http.Server{Handler:handle,ReadTimeout: ?20 * time.Second,WriteTimeout: 20 * time.Second,}listen, err := net.Listen("tcp4",s.addr)if err != nil ?{logger.Errorf("Failed to listen,err:%s",err.Error())panic(err)}server.SetKeepAlivesEnabled(false)err = server.Serve(listen)}
参考 了
- 使用
https://blog.csdn.net/cyberspecter/article/details/83308348
- https://my.oschina.net/shou1156226/blog/808613
golang http.client 遇到了 Connection reset by peer 问题
原文地址:https://www.cnblogs.com/jackluo/p/10452026.html