我在 Go http.Get、并发性和“对等方重置连接”中阅读了答案。我将
MaxConnsPerHost
设置为等于并发请求数。但同样的要求又来了,read tcp 127.0.0.1:52517->127.0.0.1:8080: read: connection reset by peer
.
这是我的客户代码:
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: %v\n", 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: %v\n", i, url, err)
return
}
fmt.Printf("%d Response from [%s] result: %s\n", i, url, string(body))
}(i)
}
wg.Wait()
}
这是我的服务器代码:
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
}
你能告诉我如何解决吗?
sudo ulimit -n 6049
sudo sysctl -w kern.ipc.somaxconn=1024