Go的http包默認(rèn)支持長連接,通過自定義Transport設(shè)置MaxIdleConns、MaxConnsPerHost、IdleConnTimeout等參數(shù)可優(yōu)化客戶端連接復(fù)用;服務(wù)端需配置ReadTimeout、WriteTimeout和IdleTimeout以合理管理空閑連接;對于SSE等流式場景,應(yīng)使用http.Flusher定期推送數(shù)據(jù)并監(jiān)聽context.Done()處理斷連;結(jié)合CloseIdleConnections和優(yōu)雅關(guān)閉避免資源泄漏。
在Golang中處理HTTP長連接,關(guān)鍵在于理解HTTP/1.1的默認(rèn)行為、合理配置net/http
包中的客戶端與服務(wù)端參數(shù),并復(fù)用底層TCP連接。Go的http.Client
和http.Server
默認(rèn)支持持久連接(Keep-Alive),但需要根據(jù)實際場景調(diào)整設(shè)置以避免資源耗盡或連接中斷。
Go的http.DefaultClient
使用Transport
自動管理連接復(fù)用。要高效處理長連接,應(yīng)自定義Transport
并設(shè)置合理的連接池參數(shù)。
示例代碼:
client := &http.Client{ Transport: &http.Transport{ MaxIdleConns: 100, MaxConnsPerHost: 50, MaxIdleConnsPerHost: 10, IdleConnTimeout: 90 * time.Second, // 與服務(wù)端Keep-Alive一致 }, }
Go的http.Server
默認(rèn)開啟Keep-Alive,但可通過字段調(diào)整行為以適應(yīng)高并發(fā)場景。
立即學(xué)習(xí)“go語言免費學(xué)習(xí)筆記(深入)”;
關(guān)鍵配置項:示例:
srv := &http.Server{ Addr: ":8080", ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, Handler: router, } log.Fatal(srv.ListenAndServe())
某些場景下需長時間保持連接傳輸數(shù)據(jù)(如實時日志推送),此時應(yīng)確保正確使用http.Flusher
。
http.ResponseWriter
轉(zhuǎn)換為http.Flusher
Flush()
強制發(fā)送緩沖數(shù)據(jù)context.Done()
監(jiān)聽中斷示例片段:
func sseHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") <pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">for i := 0; i < 10; i++ { fmt.Fprintf(w, "data: message %d\n\n", i) if f, ok := w.(http.Flusher); ok { f.Flush() } time.Sleep(1 * time.Second) }
}
長時間運行的服務(wù)需關(guān)注連接狀態(tài)??山Y(jié)合以下方式減少異常連接累積:
Transport
的CloseIdleConnections()
context.WithTimeout
控制單次請求生命周期srv.Shutdown()
優(yōu)雅關(guān)閉服務(wù)端基本上就這些。Go的標(biāo)準(zhǔn)庫已為長連接做了良好設(shè)計,重點是根據(jù)業(yè)務(wù)需求調(diào)整參數(shù),避免默認(rèn)值帶來的性能瓶頸或資源泄漏。
以上就是如何在Golang中處理HTTP長連接的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個人都需要一臺速度更快、更穩(wěn)定的 PC。隨著時間的推移,垃圾文件、舊注冊表數(shù)據(jù)和不必要的后臺進(jìn)程會占用資源并降低性能。幸運的是,許多工具可以讓 Windows 保持平穩(wěn)運行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號