永久在线亚洲观看|亚洲日韩久久AV无码|亚洲无码视频在线免费看|欧美亚洲一区二区三区视频|人人澡人人澡人人看添AV|动漫精品视频一区二区三区|亚洲国产另类久久久精品极度|极品美女熟妇又黄又爽视频一区

學到了嗎(golang終端停止運行的程序cmd命令)golang 客戶端 界面,Golang 優(yōu)雅的終止一個服務,火影之潛力無限,

保健品 nanfang 2023-06-27 02:21 163 0

1.golang終止goroutine

采用常規(guī)方式啟動一個Golang http服務時,若服務被意外終止或中斷,即未等待服務對現(xiàn)有請求連接處理并正常返回且亦未對服務停止前作一些必要的處理工作,這樣即會造成服務硬終止這種方式不是很優(yōu)雅參看如下代碼,該http服務請求路徑為根路徑,請七夕相會拋媚眼求該路徑,其會在2s后返回hello。

2.golang 中斷

var addr = flag.String("server addr", ":8080", "server address") func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { time.Sleep(2 * time.Second) fmt.Fprintln(w, "hello") }) http.ListenAndServe七夕相會拋媚眼(*addr, nil) }

3.golang退出程序

若服務啟動后,請求http://localhost:8080/,然后使用Ctrl+C立即中斷服務,服務即會立即退出(exit status 2),請求未正常返回(ERR_CONNECTION_REFUSED),連接即馬上斷了。

4.golang終端ui

接下來介紹使用http.Server的Shutdown方法結合signal.Notify來優(yōu)雅的終止服務1 Shutdown方法Golang http.Server結構體有一個終止服務的方法Shutdown,其go doc如下。

5.golang 關機

func (srv *Serve七夕相會拋媚眼r) Shutdown(ctx context.Context) error Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return七夕相會拋媚眼 to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the contexts error, otherwise it returns any error returned from closing the Servers underlying Listener(s). When Shutdown is called, Serve, ListenAndServe, and List七夕相會拋媚眼enAndServeTLS immediately return ErrServerClosed. Make sure the program doesnt exit and waits instead for Shutdown to return. Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such 七夕相會拋媚眼long-lived connections of shutdown and wait for them to close, if desired. See RegisterOnShutdown for a way to register shutdown notification functions. Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return 七夕相會拋媚眼ErrServerClosed.

6.golang shutdown

由文檔可知:使用Shutdown可以優(yōu)雅的終止服務,其不會中斷活躍連接其工作過程為:首先關閉所有開啟的監(jiān)聽器,然后關閉所有閑置連接,最后等待活躍的連接均閑置了才終止服務若傳入的context在服務完成終止前已超時,則Shutdown方法返回context的錯誤,否則返回任何由關閉服務監(jiān)聽器所引起的錯誤。

7.golang 防止 進程 退出

當Shutdown方法被調(diào)用時,Serve、ListenAndServe及ListenAndServeTLS方法會立刻返回ErrServerClosed錯誤請確保Shutdown未返回時,勿退出程七夕相會拋媚眼序對諸如WebSocket等的長連接,Shutdown不會嘗試關閉也不會等待這些連接。

8.golang close wait

若需要,需調(diào)用者分開額外處理(諸如通知諸長連接或等待它們關閉,使用RegisterOnShutdown注冊終止通知函數(shù))一旦對server調(diào)用了Shutdown,其即不可再使用了(會報ErrServerClosed錯誤)。

9.golang wait.group start

有了Shutdown方法,我們知道在服務終止前,調(diào)用該方法即可等待活躍連接正常返回,然后優(yōu)雅的關閉關于上面用到的Golang Context參數(shù),之前專門寫過一篇文章介紹了Context的使用場景(請參考七夕相會拋媚眼:。

10.golang 停止協(xié)程

Context 你使用過了吧?本文和你一起總結 Golang Context 的使用)但服務啟動后的某一時刻,程序如何知道服務被中斷了呢?服務被中斷時如何通知程序,然后調(diào)用Shutdown作處理呢?接下來看一下系統(tǒng)信號通知函數(shù)的作用。

2 signal.Notify函數(shù)signal包的Notify函數(shù)提供系統(tǒng)信號通知的能力,其go doc如下func Notify(c chan<- os.Signal, sig ...os.Signal) Notify causes package signal to relay incoming signals 七夕相會拋媚眼to c. If no signals are provided, all incoming signals will be relayed to c. Otherwise, just the provided signals will. Package signal will not block sending to c: the caller must ensure that c has sufficient buffer space to keep up with the expected signal rate. For 七夕相會拋媚眼a channel used for notification of just one signal value, a buffer of size 1 is sufficient. It is allowed to call Notify multiple times with the same channel: each call expands the set of signals sent to that channel. The only way to remove signals from the se七夕相會拋媚眼t is to call Stop. It is allowed to call Notify multiple times with different channels and the same signals: each channel receives copies of incoming signals independently. 。

由文檔可知:參數(shù)c是調(diào)用者的信號接收通道,Notify可將進入的信號轉到csig參數(shù)為需要轉發(fā)的信號類型,若不指定,所有進入的信號都將會轉到c信號不會阻塞式的發(fā)給c:調(diào)用者需確保c有足夠的七夕相會拋媚眼緩沖空間,以應對指定信號的高頻發(fā)送。

對于用于通知僅一個信號值的通道,緩沖大小為1即可同一個通道可以調(diào)用Notify多次:每個調(diào)用擴展了發(fā)送至該通道的信號集合僅可調(diào)用Stop來從信號集合移除信號允許不同的通道使用同樣的信號參數(shù)調(diào)用Notify多次:每個通道獨立的接收進入信號的副本。

綜上,有了signal.Notify,傳入一個chan并指定中斷參數(shù),這樣當系統(tǒng)中斷時,即可接收到信號參看如下代碼,當使用Ctrl+C時,c會接收到中斷信號,程序會在打印“program interrupted”語句后退出。

func main() { c := make(chan os.Signal) 七夕相會拋媚眼 signal.Notify(c, os.Interrupt) <-c log.Fatal("program interrupted") } $ go run main.go Ctrl+C 2019/06/11 17:59:11 program interrupted exit status 1

3 Server優(yōu)雅的終止接下來我們使用如上signal.Notify結合http.Server的Shutdown方法實現(xiàn)服務優(yōu)雅的終止如下代碼,Handler與文章開始時的處理七夕相會拋媚眼邏輯一樣,其會在2s后返回hello。

創(chuàng)建一個http.Server實例,指定端口與Handler聲明一個processed chan,其用來保證服務優(yōu)雅的終止后再退出主goroutine新啟一個goroutine,其會監(jiān)聽os.Interrupt信號,一旦服務被中斷即調(diào)用服務的Shutdown方法,確保活躍連接的正常返回(本代碼使用的Context超時時間為3s,大于服務Handler的處理時間,所以不會超時)。

處理完成后,關閉processed通道,最后主goroutine退出代碼同時托管在GitHub,歡迎關注(github.com/olzhy/go-excercises)var add七夕相會拋媚眼r = flag.String("server addr", ":8080", "server address") func main() { // handler handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(2 * time.Second) fmt.Fprintln(w, "hello") }) // server srv := http.七夕相會拋媚眼Server{ Addr: *addr, Handler: handler, } // make sure idle connections returned processed := make(chan struct{}) go func() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) <-c ctx, cancel := context.WithTime七夕相會拋媚眼out(context.Background(), 3*time.Second) defer cancel() if err := srv.Shutdown(ctx); nil != err { log.Fatalf("server shutdown failed, err: %v\n", err) } log.Println("server gracefully shutdown") close(processed) }() // serve err七夕相會拋媚眼 := srv.ListenAndServe() if http.ErrServerClosed != err { log.Fatalf("server not gracefully shutdown, err :%v\n", err) } // waiting for goroutine above processed <-processed } 。

原文鏈接:https://leileiluoluo.com/posts/golang-shutdown-server-graceful七夕相會拋媚眼ly.html本文作者:磊磊落落的博客,原創(chuàng)授權發(fā)布

標簽列表