http client 短链接复用(变为长连接)

 

背景:

 

  go在做服务之间调用时http client会消费系统的tcp资源(大量并发会耗费掉系统资源,资源有限),故此需要复用

 

1.复用

 

func HttpPostJson(client *http.Client, url string, jsonstr string) (bool, error) {
	var request *http.Request
	bytesData := []byte(jsonstr)
	reader := bytes.NewReader(bytesData)
	request, err = http.NewRequest("POST", url, reader)
	if err != nil {
		httpLog.Println(err)
		return false, err
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	response, err := client.Do(request)

	if err != nil {
		httpLog.Println(err)
		return false, err
	}

	if response.StatusCode != 200 {
		httpLog.Println("http resp code=", response.StatusCode, err)
		reqResult, err := ioutil.ReadAll(response.Body)
		if err != nil {
			httpLog.Println(err)
			return false, nil
		}

		httpLog.Println(reqResult)

		return false, nil
	}
        //这块关闭才能复用,循环调用即可复用,不要关闭client 
	response.Body.Close()

	return true, nil
}

 

 

也可以建立连接池

const (
	IdleConnTimeout int = 90
)

var (
   DefaultTransport *http.Transport = &http.Transport{
   	Proxy: http.ProxyFromEnvironment,
	DialContext: (&net.Dialer{
		Timeout:   60 * time.Second,
		KeepAlive: 60 * time.Second,
	}).DialContext,
	MaxIdleConns:        int(512), //不能使用参数变量,否则初始化不上
	MaxIdleConnsPerHost: int(512),
	IdleConnTimeout:	 time.Duration(IdleConnTimeout)* time.Second,
}
)

func createHTTPClient() *http.Client {
	client := &http.Client{
		Transport:DefaultTransport,
		Timeout: 60 * time.Second,
	}
	return client
}

 

 

 

你可能感兴趣的:(golang)