我有一个go程序,可以从多个协同程序生成大量的HTTP请求.运行一段时间后,程序会发出错误:connect:无法分配请求的地址.
使用netstat进行检查时,我在TIME_WAIT中获得了一个高数字(28229)的连接.
当协程的数量为3时,会发生大量的TIME_WAIT套接字,并且当它为5时严重到足以导致崩溃.
我在docker下运行Ubuntu 14.4并转到版本1.7
这是go计划.
package main
import (
"io/ioutil"
"log"
"net/http"
"sync"
)
var wg sync.WaitGroup
var url="http://172.17.0.9:3000/";
const num_coroutines=5;
const num_request_per_coroutine=100000
func get_page(){
response, err := http.Get(url)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
_, err =ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
}
}
func get_pages(){
defer wg.Done()
for i := 0; i < num_request_per_coroutine; i++{
get_page();
}
}
func main() {
for i:=0;i<num_coroutines;i++{
wg.Add(1)
go get_pages()
}
wg.Wait()
}
Run Code Online (Sandbox Code Playgroud)
这是服务器程序: …
我正在使用Go通过HTTPS发出许多请求,而且我遇到了不重用连接和用完端口的问题.我正在做的请求是一个返回JSON格式数据的API,然后我将其json.Decode转换为Go值.
根据我在这个网站上遇到的问题(#1,#2),为了让Go重新使用连接进行另一个请求,我必须在关闭之前读取整个响应的主体(注意这并不总是行为,说这里).
Previously the HTTP client's (*Response).Body.Close would try to keep
reading until EOF, hoping to reuse the keep-alive HTTP connection...
Run Code Online (Sandbox Code Playgroud)
在典型的实例中,我会使用前面链接中显示的示例,如下所示:
ioutil.ReadAll(resp.Body)
Run Code Online (Sandbox Code Playgroud)
但是因为我通过这样的代码将数据从JSON中提取出来:
...
req, _ := http.NewRequest("GET", urlString, nil)
req.Header.Add("Connection", "keep-alive")
resp, err = client.Do(req)
defer resp.Body.Close()
...
decoder := json.NewDecoder(resp.Body)
decoder.Decode(data)
Run Code Online (Sandbox Code Playgroud)
我不确定这两种方法是如何相互作用的.
所以问题是,如何确保已读取整个响应,以便以后可以将该连接重用于另一个请求?
为什么我在终止之前有多个goroutine,即使我关闭了resp.body,而我只使用了阻止调用?如果我不消耗resp.Body它只用一个goroutine终止.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"runtime"
"time"
)
func fetch() {
client := http.Client{Timeout: time.Second * 10}
url := "http://example.com"
req, err := http.NewRequest("POST", url, nil)
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
}
func main() {
fmt.Println("#Goroutines:", runtime.NumGoroutine())
fetch()
// runtime.GC()
time.Sleep(time.Second * 5)
fmt.Println("#Goroutines:", runtime.NumGoroutine())
}
Run Code Online (Sandbox Code Playgroud)
输出:
#Goroutines: 1
#Goroutines: 3
Run Code Online (Sandbox Code Playgroud)