Kalan's Blog

Kalan 頭像照片,在淡水拍攝,淺藍背景

四零二曜日電子報上線啦!訂閱訂起來

本部落主要是關於前端、軟體開發以及我在日本的生活,也會寫一些對時事的觀察和雜感
本部落格支援 RSS feed(全文章內容),可點擊下方 RSS 連結或透過第三方服務設定。若技術文章裡有程式碼語法等特殊樣式,仍建議至原網站瀏覽以獲得最佳體驗。

目前主題 亮色

我會把一些不成文的筆記或是最近的生活雜感放在短筆記,如果有興趣的話可以來看看唷!

在 Go 如何處理 connection lost?

研究了一下現在比較熱門的 sql 套件,發現幾乎都沒有像是可以即時在 connection lost 的時候跳 error 的功能。例如:nodejs 的 mysql 當中,我們可以用 connection.on(‘error’) 來監聽錯誤。

不過在 golang (至少在幾個比較熱門的套件)當中,卻沒有類似的功能。再深入一下也不難理解。

The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can be reliably observed within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the returned Tx is bound to a single connection. Once Commit or Rollback is called on the transaction, that transaction's connection is returned to DB's idle connection pool. The pool size can be controlled with SetMaxIdleConns.

簡單來講,當你呼叫 sql.Open 的時候,並不會真正建立 connection,而是在內部維護 connection pool,有需要的時候才嘗試連接。也就是說,如果你在進行一個 Query 時,由於網路問題造成 connection lost,database/sql 在底層會試著幫你 retry。

說起來這也算是好事啦,這樣就不用自己再去處理重試的邏輯。但有時候你並不想在下 query 才知道原來 connection lost 了,我希望在這之前整個應用程式就知道這件事情。

如果你想要達成類似的事情,你需要改寫底層的 Dialer 邏輯,讓 network 斷線的時候,可以即時通知你的程式。

上一篇

【golang 筆記】 如何為你的專案設定環境變數

下一篇

和 CORS 與 cookie 打交道

如果覺得這篇文章對你有幫助的話,可以考慮到下面的連結請我喝一杯 ☕️ 可以讓我平凡的一天變得閃閃發光 ✨

Buy me a coffee