go订阅mysql的binlog

Posted 11 months ago canal mysql linux go binlog curd

话不多说。如下

#ubuntu
apt install mysql-client


#alpine
apk add mariadb-client

package main

import (
	"encoding/json"

	"github.com/go-mysql-org/go-mysql/canal"
	"github.com/siddontang/go-log/log"
)

type MyEventHandler struct {
	canal.DummyEventHandler
}

func (h *MyEventHandler) OnRow(e *canal.RowsEvent) error {

	res := map[string]any{}
	for i, v := range e.Table.Columns {
		r := e.Rows[0][i]
		res[v.Name] = r
	}
	brr, _ := json.Marshal(res)
	log.Infof("%s %s %v\n", e.Action, e.Table.Name, string(brr))
	return nil
}

func (h *MyEventHandler) String() string {
	return "MyEventHandler"
}

func main() {
	cfg := canal.NewDefaultConfig()
	cfg.Addr = "localhost:3306"
	cfg.User = "root"
	cfg.Password = "aa"
	// We only care table canal_test in test db
	cfg.Dump.TableDB = "aa"
	cfg.Dump.Tables = []string{"canal_test"}

	c, err := canal.NewCanal(cfg)
	if err != nil {
		log.Fatal(err)
	}

	// Register a handler to handle RowsEvent
	c.SetEventHandler(&MyEventHandler{})

	// Start canal
	c.Run()
}

点击评论