GORM+MySQL Connection Pool
GORM μ Connection pool
νμ¬μμ λ§μ£ΌμΉ μλ¬
$ [mysql] 2024/03/11 18:37:09 packets.go:122: closing bad idle connection: unexpected read from socket
$ [mysql] 2024/03/11 18:37:09 packets.go:122: closing bad idle connection: unexpected read from socketBatch μ²λ¦¬λ₯Ό μνλ μμ λ€μ΄ λͺ¨μ¬μλ μΈμ€ν΄μ€μμ λ°μνλ€.
λΉμ¦λμ€ λ‘μ§ μ체μλ λ¬Έμ κ° μμκ³ , 컀λ₯μ κ΄λ ¨ μ€μ λ λν΄νΈλ‘ λμ΄μλ μν©μ΄μλ€.
μ¬μ€ μλΉμ€ μ 체μ μΌλ‘ 보면 MySQL μ체λ₯Ό λ§μ΄ μ°λ μν©μ μλμκ³ , λμμ μ€νλλ job μ΄ MySQL κΈ°λ°μ΄μμ΄μ 컀λ₯μ κ΄λ ¨ λ¬Έμ λ‘ μ’νλκ³ λλ²κΉ μ μμνλ€.
μ΄ κ³Όμ μμ μλ‘κ² μκ²λ μ¬μ€μ λν κΈ°λ‘.
MaxLifeTime
gorm μ sql ν¨ν€μ§μ DB κ°μ²΄λ₯Ό wrapping νκ³ μλ€.
sql.DB ꡬ쑰체μλ Stats λΌλ λ©μλκ° μλ€.
var db := &sql.DB{}
stats := db.Stats() // stats ?Stats ꡬ쑰체λ μλμ κ°μ΄ μκ²Όλ€.
// DBStats contains database statistics.
type DBStats struct {
MaxOpenConnections int // Maximum number of open connections to the database.
// Pool Status
OpenConnections int // The number of established connections both in use and idle.
InUse int // The number of connections currently in use.
Idle int // The number of idle connections.
// Counters
WaitCount int64 // The total number of connections waited for.
WaitDuration time.Duration // The total time blocked waiting for a new connection.
MaxIdleClosed int64 // The total number of connections closed due to SetMaxIdleConns.
MaxIdleTimeClosed int64 // The total number of connections closed due to SetConnMaxIdleTime.
MaxLifetimeClosed int64 // The total number of connections closed due to SetConnMaxLifetime.
}μμμ λΆν° μ½μ΄λ³΄μ.
μ΅λ 컀λ₯μ κ°μ
νμ¬ μ΄λ €μλ 컀λ₯μ κ°μ
μ¬μ©μ€μΈ 컀λ₯μ κ°μ
μ ν΄ μ»€λ₯μ κ°μ
컀λ₯μ μ λκΈ°νλ κ°μ
μ΄ λκΈ° μκ°
SetMaxIdleConnsλ‘ μΈν΄ λ«ν μ ν΄ μ»€λ₯μ κ°μSetConnMaxIdleTimeλ‘ μΈν΄ λ«ν μ ν΄ μ»€λ₯μ κ°μSetConnMaxLifetimeλ‘ μΈν΄ λ«ν 컀λ₯μ κ°μ
go μ *sql.DB ꡬ쑰체μμλ μλμ κ°μ΄ μ€μ λ€μ 컀μ€ν°λ§μ΄μ§ ν μ μλ€.
μ°Έκ³ λ‘ κΈ°λ³Έκ°μ 0μΌλ‘ λ€μ΄κ°λλ°, μ΄ κ²½μ° μ νμ΄ μλ€λ λ§μ΄λ€.
λ¬Όλ‘ μ νμ΄ μλ€κ³ ν΄μ 컀λ₯μ μ 무νλλ‘ λ§λ€μ΄λΌμλ μλ€. λν μ΄μ§κ°ν κ²½μ°μλ λΉμ¦λμ€ λ‘μ§μ λ¨Όμ κ²ν ν΄λ³΄λ κ²μ΄ μ’λ€.
GORM μμλ μλμ κ°μ΄ 컀μ€ν°λ§μ΄μ§ ν κ²μ κΆκ³ νκ³ μλ€.
μμμ μΈκΈνλ―μ΄, 컀λ₯μ κ΄λ ¨ λ¬Έμ λ‘ λ³΄κ³ λͺ¨λν°λ§μ μμνλ€.
μ£ΌκΈ°μ μΌλ‘ Stats λ₯Ό μ°μ΄λ΄€μλ MaxConn μ΄ λ§μλ 20μ λμ΄κ°μ§ μμκ³ , νΉμ΄μ¬νμΌλ‘ 보기μλ μ΄λ €μ λ€.
λ€λ§ νΉμ μμ μ΄ μ€νλ λλ§λ€ OpenConn μ΄ λμ΄λκ³ μ€μ΄λ€μ§ μλ λ¬Έμ κ° λ°κ²¬λμλ€.
μ΄μ λ λ€μκ³Ό κ°μλ€.
νΈλμμ μμμ νΈλμμ λμ λ€λ₯Έ 컀λ₯μ μ κ³μν΄μ μ§μ΄μ€λ λ κ±°μκ° μμλ€.
μ΄λ¬ν Job μ΄ μ€νλκ³ λλ©΄ 컀λ₯μ κ°μκ° νλ λμ΄λλλ°, μ΄λ° μμ μ΄ λͺ κ°κ° μλ€λ³΄λ μΌμ’ μ 컀λ₯μ λμκ° λ°μν κ²μΌλ‘ μΆμ νλ€.
νΉμ΄ν κ²μ κ°μ λ‘ μ¬μ€νμ νμλ SavePoint λ‘κ·Έκ° μ°νλ κ²λ μλκ³ , μλ¬κ° μ°ν λ€μ μ€νμ΄ λμ§ μλ κ²½μ°μ μ€νμ΄ λλ κ²½μ° λ± λΆκ·μΉμ μΈ ννλ₯Ό 보μΈλ€λ κ²μ΄λ€.
μ°μ ν΄λΉ λ κ±°μλ₯Ό λͺ¨λ μμ νκ³ , MaxConnLifetime μ ν μκ°μΌλ‘ μ€μ ν΄μ κ³μν΄μ μ’λΉ μ»€λ₯μ
μ΄ κ³μν΄μ μ΄μλ¨λ κ²μ λ°©μ§νλ€.
μμ§ μμ μ λͺ»νμ§λ§ μΆν 컀λ₯μ νμμ νλμ© ν΄λ§ν΄μ λ°μμ€λ κ΅¬μ‘°λ‘ λ³κ²½μ κ³ λ €μ€μ΄λ€.
μ°Έκ³ λ§ν¬
https://github.com/go-sql-driver/mysql/issues/1120 https://gorm.io/docs/generic_interface.html
Last updated