mysql.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package sql
  2. import (
  3. "go-common/library/log"
  4. "go-common/library/net/netutil/breaker"
  5. "go-common/library/stat"
  6. "go-common/library/time"
  7. // database driver
  8. _ "github.com/go-sql-driver/mysql"
  9. )
  10. var stats = stat.DB
  11. // Config mysql config.
  12. type Config struct {
  13. Addr string // for trace
  14. DSN string // write data source name.
  15. ReadDSN []string // read data source name.
  16. Active int // pool
  17. Idle int // pool
  18. IdleTimeout time.Duration // connect max life time.
  19. QueryTimeout time.Duration // query sql timeout
  20. ExecTimeout time.Duration // execute sql timeout
  21. TranTimeout time.Duration // transaction sql timeout
  22. Breaker *breaker.Config // breaker
  23. }
  24. // NewMySQL new db and retry connection when has error.
  25. func NewMySQL(c *Config) (db *DB) {
  26. if c.QueryTimeout == 0 || c.ExecTimeout == 0 || c.TranTimeout == 0 {
  27. panic("mysql must be set query/execute/transction timeout")
  28. }
  29. db, err := Open(c)
  30. if err != nil {
  31. log.Error("open mysql error(%v)", err)
  32. panic(err)
  33. }
  34. return
  35. }