-
測(cè)試代碼(默認(rèn)MaxIdleConns=100, MaxIdleConnsPerHost=2)
package main
import (
"io"
"io/ioutil"
"net/http"
"time"
)
func worker(client *http.Client) {
resp, _ := client.Get("[http://www.qq.com/"](http://192.168.31.1/%22);)
io.Copy(ioutil.Discard, resp.Body)
defer resp.Body.Close()
}
func worker2(client *http.Client) {
resp, _ := client.Get("[http://httpbin.org/get"](http://httpbin.org/get%22);)
io.Copy(ioutil.Discard, resp.Body) //必須讀取Body并且關(guān)閉,否者不會(huì)被復(fù)用
defer resp.Body.Close()
}
func main() {
tr := &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 2,
}
client := &http.Client{
Transport: tr,
}
worker(client)
time.Sleep(time.Second * 1)
worker(client)
time.Sleep(time.Second * 1)
worker2(client)
time.Sleep(time.Second * 1)
worker(client)
time.Sleep(time.Second * 1)
}
-
設(shè)置MaxIdleConns=MaxIdleConnsPerHost=1
-
Client第一次請(qǐng)求,源端口是55564
-
Client第二次請(qǐng)求淹真,源端口是55564
-
Client第三次請(qǐng)求,源端口是55556
-
Client第四次請(qǐng)求挨决,源端口是55568
Client前兩個(gè)請(qǐng)求對(duì)同一個(gè)host發(fā)起弥喉,復(fù)用了55564接口的鏈接允青,第三次請(qǐng)求對(duì)另外一個(gè)HOST發(fā)起,由于MaxIdleConns=1蒋得,會(huì)關(guān)閉前一個(gè)鏈接然后發(fā)起一個(gè)新的鏈接级及,第四次同樣也會(huì)關(guān)閉第三次的鏈接,重新發(fā)起窄锅。說(shuō)明MaxIdleConns限制了最大keep-alive的連接數(shù)创千,超出的連接會(huì)被關(guān)閉掉缰雇。
-
設(shè)置MaxIdleConns=2 MaxIdleConnsPerHost=1
-
Client第一次請(qǐng)求入偷,源端口是55680
-
Client第二次請(qǐng)求,源端口是55680
-
Client第三次請(qǐng)求械哟,源端口是55681
-
Client 第四次請(qǐng)求疏之,源端口是55680
Client對(duì)不同的兩個(gè)Host發(fā)起的請(qǐng)求,都復(fù)用了連接