binlog.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. package binlog
  2. import (
  3. "errors"
  4. "eta/eta_bridge/global"
  5. "eta/eta_bridge/models/index"
  6. "eta/eta_bridge/utils"
  7. "fmt"
  8. "github.com/go-mysql-org/go-mysql/canal"
  9. "github.com/go-mysql-org/go-mysql/mysql"
  10. _ "github.com/go-sql-driver/mysql"
  11. "math/rand"
  12. "net/url"
  13. "strings"
  14. "time"
  15. )
  16. var mysqlHost, mysqlUser, mysqlPwd, mysqlDb string
  17. func init() {
  18. for _, sqlConfig := range global.CONFIG.Mysql.List {
  19. if sqlConfig.AliasName == `index` {
  20. // 找出用户
  21. tmpList := strings.Split(sqlConfig.Dsn, ":")
  22. mysqlUser = tmpList[0]
  23. // 找出密码
  24. tmpList = strings.Split(strings.Join(tmpList[1:], ":"), "@")
  25. lenTmp := len(tmpList)
  26. mysqlPwd = strings.Join(tmpList[:lenTmp-1], "@")
  27. // 找出地址
  28. tmpList = strings.Split(tmpList[lenTmp-1], "tcp(")
  29. tmpList = strings.Split(tmpList[1], ")")
  30. mysqlHost = tmpList[0]
  31. // 找出数据库名称
  32. u, err := url.Parse(tmpList[1])
  33. if err != nil {
  34. panic(err) // 如果解析失败,处理错误
  35. }
  36. // 获取Path部分的内容
  37. mysqlDb = u.Path[1:]
  38. }
  39. }
  40. if mysqlHost == "" {
  41. panic("mysqlHost is empty")
  42. }
  43. //fmt.Println("HOST:", mysqlHost)
  44. //fmt.Println("user:", mysqlUser)
  45. //fmt.Println("password:", mysqlPwd)
  46. }
  47. func ListenMysql() {
  48. var err error
  49. defer func() {
  50. if err != nil {
  51. fmt.Println("数据库监听服务异常,err:", err)
  52. }
  53. }()
  54. if mysqlHost == "" {
  55. err = errors.New("mysqlHost is empty")
  56. return
  57. }
  58. //includeTableRegex := []string{
  59. // "test_hz_data.edb_info",
  60. //}
  61. includeTableRegex := []string{
  62. mysqlDb + ".edb_info$",
  63. mysqlDb + ".edb_classify$",
  64. mysqlDb + ".base_from_mysteel_chemical_index$",
  65. mysqlDb + ".base_from_smm_index$",
  66. mysqlDb + ".edb_data*",
  67. }
  68. cfg := &canal.Config{
  69. // 一个32位无符号整数,用于标识当前 Canal 实例在 MySQL 主从复制体系中的身份。这里使用了一个随机数生成器确保每次启动时分配的 ServerID 是唯一的(在1001到1099之间)。在实际生产环境中,你需要手动指定一个全局唯一的 ServerID。
  70. ServerID: uint32(rand.New(rand.NewSource(time.Now().Unix())).Intn(1000)) + 1001,
  71. // 指定 Canal 要连接的数据库类型,默认为 "mysql",表明这是一个 MySQL 数据库。
  72. Flavor: "mysql",
  73. // 设置 MySQL 服务器地址(主机名或 IP 地址)和端口,例如 "127.0.0.1:3306"。
  74. Addr: mysqlHost,
  75. User: mysqlUser,
  76. Password: mysqlPwd,
  77. // 如果设置为 true,Canal 将以原始二进制格式获取 binlog,否则将以解析后的 SQL 语句形式提供。
  78. //RawModeEnabled: false,
  79. // 是否启用半同步复制。当设置为 true 时,MySQL 主库在事务提交后会等待至少一个从库确认已接收并写入 binlog 才返回成功,提高了数据一致性。
  80. SemiSyncEnabled: false,
  81. // 是否将 MySQL 中的 decimal 类型字段解析为 Go 的 Decimal 类型,而不是 float 或者 string。如果业务中有精确小数计算的需求,应开启此选项以避免精度丢失问题。
  82. UseDecimal: true,
  83. // 用于控制初始数据导出的相关配置,在 Canal 启动时是否需要全量同步表数据。
  84. //Dump: dumpConf,
  85. // 正则表达式字符串,用于定义 Canal 应该监听哪些表的 binlog 事件。只有名称匹配该正则表达式的表才会被 Canal 同步处理。
  86. IncludeTableRegex: includeTableRegex,
  87. }
  88. // 校验mysql binlog format,目前仅支持row格式
  89. {
  90. binlogFormat, tmpErr := index.GetBinlogFormat()
  91. if tmpErr != nil {
  92. err = tmpErr
  93. return
  94. }
  95. if binlogFormat.Value != "ROW" {
  96. panic("mysql binlog format is not ROW")
  97. return
  98. }
  99. }
  100. var fileName string
  101. var position uint32
  102. fileName = global.Rc.GetStr(utils.CACHE_MYSQL_MASTER_FILENAME)
  103. position64, tmpErr := global.Rc.GetUInt64(utils.CACHE_MYSQL_MASTER_POSITION)
  104. if tmpErr != nil && tmpErr.Error() != utils.RedisNoKeyErr {
  105. panic("mysql binlog position is not found,err:" + tmpErr.Error())
  106. return
  107. }
  108. position = uint32(position64)
  109. // 如果没有从redis中获取到上次监听到的binlog的文件名称,或者位置为0,则从mysql中获取,则从 MySQL 中获取最新的文件名和位置。
  110. if fileName == `` || position == 0 {
  111. item, tmpErr := index.GetShowMaster()
  112. if tmpErr != nil {
  113. err = tmpErr
  114. return
  115. }
  116. fileName = item.File
  117. position = item.Position
  118. }
  119. c, err := canal.NewCanal(cfg)
  120. if err != nil {
  121. fmt.Println("err:", err)
  122. return
  123. }
  124. binlogHandler := &MyEventHandler{}
  125. binlogHandler.SetBinlogFileName(fileName, position)
  126. c.SetEventHandler(binlogHandler)
  127. //c.Run()
  128. pos := mysql.Position{
  129. Name: fileName,
  130. Pos: position,
  131. }
  132. err = c.RunFrom(pos)
  133. }