搜尋
首頁後端開發Golang如何更酷地實現 Go 程式熱開關功能

開發中,我們經常會有熱開關的需求,即特定功能在程式運行中的適當時候對它進行開啟或關閉。例如效能分析中所使用的 pprof 取樣,就是一種典型的熱開關。本文將討論如何將這種熱開關做得更酷。

在介紹新方案之前,我們先回顧一下,在 Go 程式中,pprof 是如何做的。

介面呼叫

對程式進行效能取樣,可能會影響到它的服務能力。因此,線上採樣一般是在指定的小塊時間範圍內進行,需要有效的開關控制。

為了做到這一點,我們一般採用在程式碼中引入 net/http/pprof 套件(其 init 函數綁定了路由功能函數)的方式。外部存取指定連接埠的 HTTP 服務時開啟採樣功能,採樣時間結束後,即關閉採集。

實作程式碼如下圖

package main

import (
 "net/http"
 _ "net/http/pprof"
)

func main() {
 go func() {
  _ = http.ListenAndServe(":8080", nil)
 }()
 ...
}

這種做法,當然沒什麼問題。我們可以學習它,將其他的開關功能也做成 HTTP 服務。但,還有其他更酷的方式嗎?

信号通知

信号处理与 Go 程序的优雅退出一文中,我们谈论过信号机制,它用以向应用程序发送某种事件通知。

我们可以将基于接口触发的方式改为信号通知。

首先,构造采样功能函数(对应于 net/http/pprof 包下 init 函数中绑定的路由功能函数)。

func RegisterSignalForProfiling(sig os.Signal) {
 ch := make(chan os.Signal)
 started := false
 signal.Notify(ch, sig)

 go func() {
  var memoryProfile, cpuProfile, traceProfile *os.File
  for range ch {
   if started {
    pprof.StopCPUProfile()
    trace.Stop()
    pprof.WriteHeapProfile(memoryProfile)
    memoryProfile.Close()
    cpuProfile.Close()
    traceProfile.Close()
    started = false
   } else {
    cpuProfile, _ = os.Create("cpu.pprof")
    memoryProfile, _ = os.Create("memory.pprof")
    traceProfile, _ = os.Create("runtime.trace")
    pprof.StartCPUProfile(cpuProfile)
    trace.Start(traceProfile)
    started = true
   }
  }
 }()
}

在上述函数中,我们定义了接收信号通道<span style="font-size: 15px;">ch</span>,通过<span style="font-size: 15px;">signal.Notify(ch, sig)</span>将指定的通知信号<span style="font-size: 15px;">sig</span><span style="font-size: 15px;">ch</span>进行绑定。<span style="font-size: 15px;">for range ch</span> 将阻塞等待外部信号<span style="font-size: 15px;">sig</span>,随着<span style="font-size: 15px;">sig</span>信号的到来,交替进入开启或关闭采样的逻辑。

<span style="font-size: 15px;">main</span>函数中,就可以这样替代<span style="font-size: 15px;">http.ListenAndServe(":8080", nil)</span>了。

package main

import (
  "syscall"
  ...
)

func main() {
  RegisterSignalForProfiling(syscall.Signal(31))
 ...
}

在 linux 系统,可以通过<span style="font-size: 15px;">kill -signal_number pid</span>命令向程序发送指定信号。

如上代码所示,我们硬编码指定的采样开关信号值是 31。因此,当程序运行起来后,我们在控制台输入<span style="font-size: 15px;">kill -31 pid</span> 命令,即可开启采样,再次输入<span style="font-size: 15px;">kill -31 pid</span>命令,就关闭了采样。

依葫芦画瓢,我们再来一个打印 goroutine 堆栈信息的热开关函数,是不是很酷?

func RegisterSignalForPrintStack(sig os.Signal) {
 ch := make(chan os.Signal)
 signal.Notify(ch, sig)

 go func() {
  for range ch {
   buffer := make([]byte, 1024*1024*4)
   runtime.Stack(buffer, true)
   fmt.Println(string(buffer))
  }
 }()
}

总结

热开关是一个很简单常用的功能,无非是选择何种触发与等待方式。基于接口的调用更适合于远程控制,基于信号则便于本地控制。

以上是如何更酷地實現 Go 程式熱開關功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:Go语言进阶学习。如有侵權,請聯絡admin@php.cn刪除
去其他語言:比較分析去其他語言:比較分析Apr 28, 2025 am 12:17 AM

goisastrongchoiceforprojectsneedingsimplicity,績效和引發性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

比較以其他語言的靜態初始化器中的初始化功能比較以其他語言的靜態初始化器中的初始化功能Apr 28, 2025 am 12:16 AM

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

GO中初始功能的常見用例GO中初始功能的常見用例Apr 28, 2025 am 12:13 AM

thecommonusecasesfortheinitfunctionoare:1)加載configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

GO中的頻道:掌握際際交流GO中的頻道:掌握際際交流Apr 28, 2025 am 12:04 AM

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

包裝錯誤:將上下文添加到錯誤鏈中包裝錯誤:將上下文添加到錯誤鏈中Apr 28, 2025 am 12:02 AM

在Go中,可以通過errors.Wrap和errors.Unwrap方法來包裝錯誤並添加上下文。 1)使用errors包的新功能,可以在錯誤傳播過程中添加上下文信息。 2)通過fmt.Errorf和%w包裝錯誤,幫助定位問題。 3)自定義錯誤類型可以創建更具語義化的錯誤,增強錯誤處理的表達能力。

使用GO開發時的安全考慮使用GO開發時的安全考慮Apr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

了解GO的錯誤接口了解GO的錯誤接口Apr 27, 2025 am 12:16 AM

Go的錯誤接口定義為typeerrorinterface{Error()string},允許任何實現Error()方法的類型被視為錯誤。使用步驟如下:1.基本檢查和記錄錯誤,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。 2.創建自定義錯誤類型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。 3.使用錯誤包裝(自Go1.13起)來添加上下文而不丟失原始錯誤信息,

並發程序中的錯誤處理並發程序中的錯誤處理Apr 27, 2025 am 12:13 AM

對效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,enplionErrorWatchers,Instertimeout,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErtopassErrorsErtopassErrorsErrorsErrorsFromGoroutInestOthemainFunction.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器