当我进行负载测试时,我收到 dial tcp : socket: Too much open files 错误。通过设置 ulimit 其工作正常,但是在不设置 ulimit 的情况下还有其他解决方案吗?
代码:
package main
import (
"fmt"
"io"
"io/ioutil"
"encoding/json"
"net/http"
)
type Struct_Response struct {
Meta struct {
Requestid string
}
}
var HttpClient = &http.Client{}
func main(){
apiUrl := "http://example.com"
JsonStr :="teststr"
conn_token :="1233333333333"
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(JsonStr))
if err!=nil{
fmt.Println(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("requestid", "1234")
req.Header.Set("Authorization", "Bearer "+conn_token)
req.Header.Set("Connection", "close")
resp, err := HttpClient.Do(req)
req.Close=true
if resp!=nil && resp.StatusCode==200 {
body, _ := ioutil.ReadAll(resp.Body)
var Responce Struct_Response
err := json.Unmarshal([]byte(string(body)), &Responce)
if err != nil {
fmt.Println(err)
}
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢。
您的问题可能是您没有完全关闭连接,这会导致在重用 TCP 端口客户端端口号之前添加延迟。
在上面的代码示例中,仅当状态为 200 时才会使用和关闭响应主体。您应该始终使用/关闭存在的响应主体。