還記得怎么啟動一個HTTP Server么?
package mainimport ( "net" "net/http")func main() { // 方式1 err := http.ListenAndServe(":8080", nil) if err != nil { panic(err) } // 方式2 // server := &http.Server{Addr: ":8080"} // err := server.ListenAndServe() // if err != nil { // panic(err) // }}
ListenAndServe在不出錯的情況下,會一直阻塞在這個位置,如何停止這樣的一個HTTP Server呢?
CTRL+C是結束一個進程常用的方式,它和kill pid或者kill -l 15 pid命令本質上沒有任何區別,他們都是向進程發送了SIGTERM信號。因為程序沒有設置對SIGTERM信號的處理程序,所以系統默認的信號處理程序結束了我們的進程
這會帶來什么問題?
在服務器的進程被殺死時,我們的服務器可能正在處理請求并未完成。因此對于客戶端產生了一個預期外的錯誤
curl -v --max-time 4 127.0.0.1:8009/foo* Connection #0 to host 127.0.0.1 left intact* Trying 127.0.0.1:8009...* Connected to 127.0.0.1 (127.0.0.1) port 8009 (#0)> GET /foo HTTP/1.1> Host: 127.0.0.1:8009> User-Agent: curl/7.86.0> Accept: */*> * Empty reply from server* Closing connection 0curl: (52) Empty reply from server
如果有nginx代理,因為upstream的中斷,nginx會產生502的響應
curl -v --max-time 11 127.0.0.1:8010/foo* Trying 127.0.0.1:8010...* Connected to 127.0.0.1 (127.0.0.1) port 8010 (#0)> GET /foo HTTP/1.1> Host: 127.0.0.1:8010> User-Agent: curl/7.86.0> Accept: */*> * Mark bundle as not supporting multiuse< HTTP/1.1 502 Bad Gateway< Server: nginx/1.25.3< Date: Sat, 02 Dec 2023 10:14:33 GMT< Content-Type: text/html< Content-Length: 497< Connection: keep-alive< ETag: "6537cac7-1f1"
優雅關閉(graceful shutdown)指的是我們的HTTP Server關閉前既拒絕新來的請求,又正確的處理完正在進行中的請求,隨后進程退出。如何實現?
本文鏈接:http://www.www897cc.com/showinfo-26-37244-0.html深入理解Go標準庫-http server的優雅關閉
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 使用Ruff改善Python編程風格