I read the answer in Go http.Get, concurrency, and “Connection reset by peer”. I set the MaxConnsPerHost
to equal the number of concurrent requests. But the same request comes again, read tcp 127.0.0.1:52517->127.0.0.1:8080: read: connection reset by peer
.
Here is my client code:
package main
import (
"fmt"
"io"
"net/http"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
for i := 0; i < 400; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
url := "http://127.0.0.1:8080/sleep"
rt := http.Transport{
MaxIdleConns: 400,
MaxIdleConnsPerHost: 400,
MaxConnsPerHost: 400,
IdleConnTimeout: 20 * time.Second,
DisableKeepAlives: false,
}
client := http.Client{
Transport: &rt,
}
resp, err := client.Get(url)
if err != nil {
fmt.Printf("%d Request to [%s] failed, error: %vn", i, url, err)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%d Failed to read response from [%s], error: %vn", i, url, err)
return
}
fmt.Printf("%d Response from [%s] result: %sn", i, url, string(body))
}(i)
}
wg.Wait()
}
And Here is my server code:
package main
import (
"github.com/gin-gonic/gin"
"time"
)
func main() {
r := gin.Default()
r.GET("/sleep", func(c *gin.Context) {
time.Sleep(10)
c.JSON(200, gin.H{
"message": "Slept for 10 seconds",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
Can you tell me how to fix it?
3
In macOS, set the parameters.
sudo ulimit -n 6049
sudo sysctl -w kern.ipc.somaxconn=1024
https://github.com/golang/go/issues/20960#issuecomment-465998114
In Linux, set:
sudo ulimit -n 6049
sudo sysctl -w net.core.somaxconn=1024
1