分享一款go编写兼容mysql服务协议的库go-mysql
go-mysql 是一个专注于处理 MySQL 网络协议和复制的纯 Go 语言库。
该项目提供了 Replication 包来处理 MySQL 复制协议,允许用户从主服务器同步 binlog 数据,并且支持使用 GTID 进行复制。
import ( "github.com/go-mysql-org/go-mysql/replication" "os" ) // Create a binlog syncer with a unique server id, the server id must be different from other MySQL's. // flavor is mysql or mariadb cfg := replication.BinlogSyncerConfig { ServerID: 100, Flavor: "mysql", Host: "127.0.0.1", Port: 3306, User: "root", Password: "", } syncer := replication.NewBinlogSyncer(cfg) // Start sync with specified binlog file and position streamer, _ := syncer.StartSync(mysql.Position{binlogFile, binlogPos}) // or you can start a gtid replication like // streamer, _ := syncer.StartSyncGTID(gtidSet) // the mysql GTID set likes this "de278ad0-2106-11e4-9f8e-6edd0ca20947:1-2" // the mariadb GTID set likes this "0-1-100" for { ev, _ := streamer.GetEvent(context.Background()) // Dump event ev.Dump(os.Stdout) } // or we can use a timeout context for { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) ev, err := streamer.GetEvent(ctx) cancel() if err == context.DeadlineExceeded { // meet timeout continue } ev.Dump(os.Stdout) }
此外,还有一个 Canal 包,它能够将 MySQL 数据进行初始同步,并通过 binlog 实时同步变更数据,要求 binlog 使用 ROW 格式。
package main import ( "github.com/go-mysql-org/go-mysql/canal" "github.com/siddontang/go-log/log" ) type MyEventHandler struct { cana...
点击查看剩余70%
网友评论