connector.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package mysql
  2. import (
  3. "database/sql"
  4. "github.com/go-sql-driver/mysql"
  5. "rocommon"
  6. "rocommon/socket"
  7. "rocommon/util"
  8. "sync"
  9. "time"
  10. )
  11. type MysqlConnector struct {
  12. MySQLParameter
  13. socket.NetServerNodeProperty
  14. db *sql.DB
  15. dbMutex sync.RWMutex
  16. reconDur time.Duration
  17. }
  18. func (this *MysqlConnector) dbConn() *sql.DB {
  19. this.dbMutex.RLock()
  20. defer this.dbMutex.RUnlock()
  21. return this.db
  22. }
  23. func (this *MysqlConnector) IsReady() bool {
  24. return this.dbConn() != nil
  25. }
  26. func (this *MysqlConnector) Operate(cb func(client interface{}) interface{}) interface{} {
  27. return cb(this.dbConn())
  28. }
  29. func (this *MysqlConnector) TypeOfName() string {
  30. return "mysqlConnector"
  31. }
  32. func (this *MysqlConnector) SetReconnectDuration(v time.Duration) {
  33. this.reconDur = v
  34. }
  35. func (this *MysqlConnector) tryConnect() {
  36. _, err := mysql.ParseDSN(this.GetAddr())
  37. if err != nil {
  38. util.ErrorF("invalid mysql dns=%v err=%v", this.GetAddr(), err)
  39. return
  40. }
  41. //util.InfoF("connect to mysql name=%v addr=%v dbname=%v", this.GetName(), cfg.Addr, cfg.DBName)
  42. db, err := sql.Open("mysql", this.GetAddr())
  43. if err != nil {
  44. util.ErrorF("open mysql database err=%v", err)
  45. return
  46. }
  47. err = db.Ping()
  48. if err != nil {
  49. util.ErrorF("ping err=%v", err)
  50. return
  51. }
  52. db.SetMaxIdleConns(int(this.PoolConnCount))
  53. db.SetMaxIdleConns(int(this.PoolConnCount))
  54. this.dbMutex.Lock()
  55. this.db = db
  56. this.dbMutex.Unlock()
  57. }
  58. func (this *MysqlConnector) Start() rocommon.ServerNode {
  59. for {
  60. this.tryConnect()
  61. if this.reconDur == 0 || this.IsReady() {
  62. break
  63. }
  64. time.Sleep(this.reconDur)
  65. }
  66. return this
  67. }
  68. func (this *MysqlConnector) Stop() {
  69. db := this.dbConn()
  70. if db != nil {
  71. db.Close()
  72. }
  73. }
  74. func init() {
  75. socket.RegisterServerNode(func() rocommon.ServerNode {
  76. node := new(MysqlConnector)
  77. node.MySQLParameter.Init()
  78. return node
  79. })
  80. }