golang http請求變為長鏈接


在項目中使用一個第三方的api,發現每次請求都在創建一個http請求,用完既丟.

於是查閱資料對其修改變為一個靜態字段,重復使用

 

1. 創建一個http請求池

package client

import (
    "net"
    "net/http"
    "time"
)
const (
    IdleConnTimeout int = 90
)

var (
    longTransport *http.Transport = &http.Transport{
        Proxy:http.ProxyFromEnvironment,
        DialContext:(&net.Dialer{
            Timeout:60 * time.Second,
            KeepAlive:60 * time.Second,
        }).DialContext,
        MaxIdleConns:           512,
        MaxIdleConnsPerHost:    512,
        IdleConnTimeout:        time.Duration(IdleConnTimeout)* time.Second,
    }
)

func NewClient() *http.Client{
    return &http.Client{
        //Transport:     http.DefaultTransport,       // http 默認長鏈接設置
        Transport:longTransport,                        
        Timeout:time.Second * 60,
    }
}

2. mian包中對其請求測試

func main() {

    request, err := http.NewRequest("GET", "https://wiki.biligame.com/blhx/%E9%A6%96%E9%A1%B5", nil)
    if err != nil {
        log.Println(err)
    }

    /*
        循環三次長鏈接所需時間
                one                teo            three          four
            1.184.0079ms    181.3672ms        124.6007ms        141.4977ms
            2.138.5282ms    100.0047ms      171.2998ms        100.2751ms
            3.140.0335ms    109.0296ms      111.2939ms        111.7786ms
        結果為除了第一次連接,之后的連接比第一次連接時間少
     */
    for i:=0;i<3 ; i++ {
        startTime := time.Now()

        response, err := LongClient.Do(request)
        if response.StatusCode != 200 {
            log.Println("http resp code=", response.StatusCode, err)
        }
        log.Printf("response success is code = %d",response.StatusCode)

        endTime := time.Now()
        log.Println("request start wiat for time :",startTime.String())
        log.Println("request end wiat for time :",endTime.String())
        log.Printf("response wiat for time : %s",endTime.Sub(startTime).String()) // 單次測試164.0372ms
        response.Body.Close()
    }
}

 

而不使用鏈接池,循環三次,每次創建HTTP請求

func main() {

    request,_ := http.NewRequest("GET","https://wiki.biligame.com/blhx/%E9%A6%96%E9%A1%B5",nil)

    /*
        循環三次長鏈接所需時間
                one                teo            three          four
            1.230.7228ms    202.0134ms        225.9359ms        171.0883ms
            2.159.8703ms    152.1385ms      148.9046ms        102.9468ms
            3.133.9989ms    142.9298ms      135.4251ms        122.8589ms
     */
    for i:=0;i<3 ;i++  {

        client := &http.Client{}

        startTime := time.Now()
        response, err := client.Do(request)

        if response.StatusCode != 200 {
            log.Println("http resp code=", response.StatusCode, err)
            reqResult, err := ioutil.ReadAll(response.Body)
            if err != nil {
                log.Println(err)
            }
            log.Println(string(reqResult))
        }
        log.Printf("response success is code = %d",response.StatusCode)

        endTime := time.Now()
        log.Println("request start wiat for time :",startTime.String())
        log.Println("request end wiat for time :",endTime.String())
        log.Printf("response wiat for time : %s",endTime.Sub(startTime).String()) //152.988ms
        response.Body.Close()
    }
}

 

第一次鏈接時間通常都比鏈接池第一次鏈接時間長,第二次,第三次對比起來減少 10%-20% 等待時間

 

 

 

 

 

ohter http包默認鏈接池設置

// DefaultTransport is the default implementation of Transport and is
// used by DefaultClient. It establishes network connections as needed
// and caches them for reuse by subsequent calls. It uses HTTP proxies
// as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and
// $no_proxy) environment variables.
var DefaultTransport RoundTripper = &Transport{
    Proxy: ProxyFromEnvironment,
    DialContext: (&net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
        DualStack: true,
    }).DialContext,
    ForceAttemptHTTP2:     true,
    MaxIdleConns:          100,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ExpectContinueTimeout: 1 * time.Second,
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM