binlog.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package binlog
  2. import (
  3. "eta/eta_api/models/binlog"
  4. "eta/eta_api/utils"
  5. "fmt"
  6. "math/rand"
  7. "strconv"
  8. "time"
  9. "github.com/go-mysql-org/go-mysql/canal"
  10. "github.com/go-mysql-org/go-mysql/mysql"
  11. _ "github.com/go-sql-driver/mysql"
  12. )
  13. func ListenMysql() {
  14. var err error
  15. defer func() {
  16. if err != nil {
  17. fmt.Println("数据库监听服务异常,err:", err)
  18. }
  19. }()
  20. if utils.MYSQL_DATA_BINLOG_URL == "" {
  21. panic("mysql url is empty")
  22. }
  23. if utils.MYSQL_DATA_BINLOG_USER == "" {
  24. panic("mysql user is empty")
  25. }
  26. if utils.MYSQL_DATA_BINLOG_PWD == "" {
  27. panic("mysql password is empty")
  28. }
  29. if utils.MYSQL_DATA_BINLOG_DB == "" {
  30. panic("mysql db is empty")
  31. }
  32. includeTableRegex := []string{
  33. utils.MYSQL_DATA_BINLOG_DB + ".edb_info$",
  34. // utils.MYSQL_DATA_BINLOG_DB + ".edb_classify$",
  35. // utils.MYSQL_DATA_BINLOG_DB + ".base_from_mysteel_chemical_index$",
  36. // utils.MYSQL_DATA_BINLOG_DB + ".base_from_smm_index$",
  37. // utils.MYSQL_DATA_BINLOG_DB + ".edb_data*",
  38. }
  39. // 主从复制的身份id配置,必须全局唯一,如果没有配置的话,那么会随机生成一个
  40. var serverId uint32
  41. if utils.MYSQL_DATA_BINLOG_SERVER_ID != "" {
  42. id, _ := strconv.ParseUint(utils.MYSQL_DATA_BINLOG_SERVER_ID, 10, 32)
  43. serverId = uint32(id)
  44. }
  45. if serverId == 0 {
  46. serverId = uint32(rand.New(rand.NewSource(time.Now().Unix())).Intn(1000)) + 1001
  47. }
  48. cfg := &canal.Config{
  49. // 一个32位无符号整数,用于标识当前 Canal 实例在 MySQL 主从复制体系中的身份。这里使用了一个随机数生成器确保每次启动时分配的 ServerID 是唯一的(在1001到1099之间)。在实际生产环境中,你需要手动指定一个全局唯一的 ServerID。
  50. ServerID: serverId,
  51. // 指定 Canal 要连接的数据库类型,默认为 "mysql",表明这是一个 MySQL 数据库。
  52. Flavor: "mysql",
  53. // 设置 MySQL 服务器地址(主机名或 IP 地址)和端口,例如 "127.0.0.1:3306"。
  54. Addr: utils.MYSQL_DATA_BINLOG_URL,
  55. User: utils.MYSQL_DATA_BINLOG_USER,
  56. Password: utils.MYSQL_DATA_BINLOG_PWD,
  57. // 如果设置为 true,Canal 将以原始二进制格式获取 binlog,否则将以解析后的 SQL 语句形式提供。
  58. //RawModeEnabled: false,
  59. // 是否启用半同步复制。当设置为 true 时,MySQL 主库在事务提交后会等待至少一个从库确认已接收并写入 binlog 才返回成功,提高了数据一致性。
  60. SemiSyncEnabled: false,
  61. // 是否将 MySQL 中的 decimal 类型字段解析为 Go 的 Decimal 类型,而不是 float 或者 string。如果业务中有精确小数计算的需求,应开启此选项以避免精度丢失问题。
  62. UseDecimal: true,
  63. // 用于控制初始数据导出的相关配置,在 Canal 启动时是否需要全量同步表数据。
  64. //Dump: dumpConf,
  65. // 正则表达式字符串,用于定义 Canal 应该监听哪些表的 binlog 事件。只有名称匹配该正则表达式的表才会被 Canal 同步处理。
  66. IncludeTableRegex: includeTableRegex,
  67. }
  68. // 校验mysql binlog format,目前仅支持row格式
  69. {
  70. binlogFormat, tmpErr := binlog.GetBinlogFormat()
  71. if tmpErr != nil {
  72. err = tmpErr
  73. return
  74. }
  75. if binlogFormat.Value != "ROW" {
  76. panic("mysql binlog format is not ROW")
  77. return
  78. }
  79. }
  80. // 获取上一次启动时的binlog文件名称和位置
  81. fileName, position, err := getBinlogNamePosition()
  82. if err != nil {
  83. return
  84. }
  85. // 修改记录本次启动时的binlog文件名称和位置
  86. modifyBinlogNamePosition(fileName, position)
  87. // 定时修改binlog文件名称和位置
  88. go timingModifyBinlogNamePosition()
  89. c, err := canal.NewCanal(cfg)
  90. if err != nil {
  91. fmt.Println("err:", err)
  92. return
  93. }
  94. utils.FileLog.Debug("记录上一次启动时的fileName:", fileName, ";position:", position)
  95. binlogHandler := &EdbEventHandler{}
  96. binlogHandler.SetBinlogFileName(fileName, position)
  97. c.SetEventHandler(binlogHandler)
  98. //c.Run()
  99. pos := mysql.Position{
  100. Name: fileName,
  101. Pos: position,
  102. }
  103. err = c.RunFrom(pos)
  104. }
  105. // getBinlogNamePosition
  106. // @Description: 获取当前binlog文件名称和位置
  107. // @author: Roc
  108. // @datetime 2024-05-17 13:18:19
  109. // @return fileName string
  110. // @return position uint32
  111. // @return err error
  112. func getBinlogNamePosition() (fileName string, position uint32, err error) {
  113. // 优先从redis获取
  114. fileName = utils.Rc.GetStr(utils.CACHE_MYSQL_DATA_FILENAME)
  115. position64, err := utils.Rc.GetUInt64(utils.CACHE_MYSQL_DATA_POSITION)
  116. if err != nil {
  117. if err.Error() != utils.RedisNoKeyErr {
  118. panic("mysql binlog position is not found,err:" + err.Error())
  119. return
  120. }
  121. err = nil
  122. }
  123. position = uint32(position64)
  124. // 如果没有从redis中获取到上次监听到的binlog的文件名称,或者位置为0,则从mysql中获取,则从 MySQL 中获取最新的文件名和位置。
  125. if fileName == `` || position == 0 {
  126. // binlog文件名
  127. fileNameKey := binlog.BinlogFileNameKey
  128. fileNameLog, tmpErr := binlog.GetBusinessSysInteractionLogByKey(fileNameKey)
  129. if tmpErr == nil {
  130. fileName = fileNameLog.InteractionKey
  131. }
  132. // binlog位置
  133. positionKey := binlog.BinlogPositionKey
  134. positionLog, tmpErr := binlog.GetBusinessSysInteractionLogByKey(positionKey)
  135. if tmpErr == nil {
  136. positionStr := positionLog.InteractionKey
  137. positionInt, tmpErr := strconv.Atoi(positionStr)
  138. if tmpErr == nil {
  139. position = uint32(positionInt)
  140. }
  141. }
  142. }
  143. // 如果从表中没有取到数据,则从mysql中获取,则从 MySQL 中获取最新的文件名和位置。
  144. if fileName == `` || position == 0 {
  145. item, tmpErr := binlog.GetShowMaster()
  146. if tmpErr != nil {
  147. err = tmpErr
  148. return
  149. }
  150. fileName = item.File
  151. position = item.Position
  152. }
  153. return
  154. }
  155. // modifyBinlogNamePosition
  156. // @Description: 修改记录本次启动时的binlog文件名称和位置
  157. // @author: Roc
  158. // @datetime 2024-05-17 11:32:32
  159. // @param fileName string
  160. // @param position uint32
  161. // @return err error
  162. func modifyBinlogNamePosition(fileName string, position uint32) {
  163. var err error
  164. defer func() {
  165. if err != nil {
  166. utils.FileLog.Error("修改binlog文件名称和位置异常,fileName", fileName, ",position:", position, ",err:", err)
  167. }
  168. }()
  169. // fileName 变更
  170. fileNameKey := binlog.BinlogFileNameKey
  171. fileNameLog, err := binlog.GetBusinessSysInteractionLogByKey(fileNameKey)
  172. if err != nil {
  173. if err.Error() != utils.ErrNoRow() {
  174. return
  175. }
  176. err = nil
  177. fileNameLog = &binlog.BusinessSysInteractionLog{
  178. //ID: 0,
  179. InteractionKey: fileNameKey,
  180. InteractionVal: fileName,
  181. Remark: "mysql中binlog的filename名称",
  182. ModifyTime: time.Now(),
  183. CreateTime: time.Now(),
  184. }
  185. err = fileNameLog.Create()
  186. if err != nil {
  187. return
  188. }
  189. } else {
  190. fileNameLog.InteractionVal = fileName
  191. fileNameLog.ModifyTime = time.Now()
  192. err = fileNameLog.Update([]string{"InteractionVal", "ModifyTime"})
  193. if err != nil {
  194. return
  195. }
  196. }
  197. // position 变更
  198. positionKey := binlog.BinlogPositionKey
  199. positionLog, err := binlog.GetBusinessSysInteractionLogByKey(positionKey)
  200. if err != nil {
  201. if err.Error() != utils.ErrNoRow() {
  202. return
  203. }
  204. err = nil
  205. positionLog = &binlog.BusinessSysInteractionLog{
  206. //ID: 0,
  207. InteractionKey: positionKey,
  208. InteractionVal: fmt.Sprint(position),
  209. Remark: "mysql中binlog的position位置",
  210. ModifyTime: time.Now(),
  211. CreateTime: time.Now(),
  212. }
  213. err = positionLog.Create()
  214. if err != nil {
  215. return
  216. }
  217. } else {
  218. positionLog.InteractionVal = fmt.Sprint(position)
  219. positionLog.ModifyTime = time.Now()
  220. err = positionLog.Update([]string{"InteractionVal", "ModifyTime"})
  221. if err != nil {
  222. return
  223. }
  224. }
  225. return
  226. }
  227. // timingModifyBinlogNamePosition
  228. // @Description: 定时修改binlog文件名称和位置
  229. // @author: Roc
  230. // @datetime 2024-05-17 13:08:13
  231. func timingModifyBinlogNamePosition() {
  232. for {
  233. // 延时30s执行
  234. time.Sleep(30 * time.Second)
  235. // 获取最新的binlog文件名称和位置
  236. fileName, position, err := getBinlogNamePosition()
  237. if err != nil {
  238. return
  239. }
  240. if fileName != `` && position != 0 {
  241. // 修改记录本次启动时的binlog文件名称和位置
  242. modifyBinlogNamePosition(fileName, position)
  243. }
  244. }
  245. }