Binlog日志解析

一、使用命令行工具 mysqlbinlog 读取 binlog

这是最直接、最常用的方法:

1. 查看 binlog 文件列表

SHOW BINARY LOGS;

2. 使用 mysqlbinlog 工具查看内容

mysqlbinlog mysql-bin.000001

3. 查看详细内容(行模式解码)

mysqlbinlog -v --base64-output=DECODE-ROWS mysql-bin.000001

4. 按时间、位置过滤

mysqlbinlog --start-datetime="2024-06-01 12:00:00" --stop-datetime="2024-06-01 13:00:00" mysql-bin.000001
mysqlbinlog --start-position=12345 --stop-position=67890 mysql-bin.000001

5. 远程读取 binlog

mysqlbinlog -h 192.168.1.100 -u root -p --read-from-remote-server mysql-bin.000001

二、通过 SQL 语句读取 binlog

此方法只能查看 statement 格式的 binlog,且信息有限:

SHOW BINLOG EVENTS IN 'mysql-bin.000001';

三、通过编程方式读取 binlog

适合做实时同步、数据订阅等场景。

1. Java 方式(举例)

推荐用 mysql-binlog-connector-java

import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.*;

public class BinlogReader {
    public static void main(String[] args) throws Exception {
        BinaryLogClient client = new BinaryLogClient("localhost", 3306, "root", "password");
        client.registerEventListener(event -> {
            System.out.println(event.getHeader() + " " + event.getData());
        });
        client.connect();
    }
}

2. Python 方式

用 mysql-replication 库:

from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import WriteRowsEvent, UpdateRowsEvent, DeleteRowsEvent

stream = BinLogStreamReader(
    connection_settings={"host": "localhost", "user": "root", "passwd": "password"},
    server_id=100,
    blocking=True,
    only_events=[WriteRowsEvent, UpdateRowsEvent, DeleteRowsEvent]
)

for binlogevent in stream:
    for row in binlogevent.rows:
        print(row)
stream.close()

四、binlog 日志相关配置

  • 确保 my.cnf 配置了 log_bin 并设置了合适的 binlog_format(推荐 ROW)。
  • 读取 binlog 需要有 REPLICATION SLAVE 或 REPLICATION CLIENT 权限。

五、常见问题

  • binlog 文件默认存放在 MySQL 数据目录下,文件名如 mysql-bin.000001
  • binlog 过大时,建议用时间/位置过滤。
  • 行格式 binlog 需加 -v --base64-output=DECODE-ROWS 查看详细变更。

总结

  • 查看内容:用 mysqlbinlog 工具最方便。
  • 实时消费:用 Java(Canal、mysql-binlog-connector-java)、Python(mysql-replication)等解析库。
  • SQL 命令:只能查部分内容,主要用于定位和管理。

六、使用阿里巴巴 Canal

Canal 是阿里开源的 MySQL binlog 增量订阅&消费组件,本质上是模拟 MySQL slave 协议,实时解析 binlog,常用于数据同步、消息推送等场景。

1. Canal 的工作原理

  • Canal 作为客户端,连接到 MySQL,模拟 slave,订阅 binlog。
  • Canal 解析 binlog,并以 Java 对象形式输出变更事件。

2. 快速使用 Canal

(1)下载 Canal
(2)配置 canal.properties 和 instance.properties
  • 配置 MySQL 地址、账号、binlog 信息等。
(3)Java 客户端消费 Canal 消息

使用 Canal 提供的 Java API(canal-client):

CanalConnector connector = CanalConnectors.newSingleConnector(
    new InetSocketAddress("127.0.0.1", 11111), "example", "", "");

connector.connect();
connector.subscribe(".*\\..*"); // 订阅所有库表
connector.rollback();

while (true) {
    Message message = connector.getWithoutAck(100); // 获取最多100条
    List<CanalEntry.Entry> entries = message.getEntries();
    for (CanalEntry.Entry entry : entries) {
        // 解析 entry,获取变更数据
        // 主要关注 entry.getEntryType() == ROWDATA
    }
    connector.ack(message.getId());
}
connector.disconnect();
  • 解析 CanalEntry.Entry 可获取表名、操作类型、变更前后数据等。

七、使用 open-replicator

open-replicator 是一个较轻量级的 Java binlog 解析库,直接解析 MySQL binlog 协议。

1. 快速使用 open-replicator

(1)添加依赖
<dependency>
  <groupId>com.github.shyiko</groupId>
  <artifactId>mysql-binlog-connector-java</artifactId>
  <version>0.26.0</version>
</dependency>

(推荐用 mysql-binlog-connector-java,open-replicator 已较久未维护)

(2)示例代码
import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.*;

public class BinlogReader {
    public static void main(String[] args) throws Exception {
        BinaryLogClient client = new BinaryLogClient("localhost", 3306, "root", "password");
        client.registerEventListener(event -> {
            EventData data = event.getData();
            if (data instanceof WriteRowsEventData) {
                System.out.println("Insert: " + data);
            } else if (data instanceof UpdateRowsEventData) {
                System.out.println("Update: " + data);
            } else if (data instanceof DeleteRowsEventData) {
                System.out.println("Delete: " + data);
            }
        });
        client.connect();
    }
}
  • 支持实时监听 binlog,获取 insert/update/delete 等事件。

八、MySQL 配置要求

  1. 开启 binlog
    my.cnf 配置:

    server-id=1
    log_bin=mysql-bin
    binlog_format=ROW
    
  2. 账号权限
    需要 REPLICATION SLAVE 或 REPLICATION CLIENT 权限。

    GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'user'@'host' IDENTIFIED BY 'password';
    FLUSH PRIVILEGES;
    

九、参考项目


总结

Java 读取 MySQL binlog,推荐用 Canal(功能强大,社区活跃)或 mysql-binlog-connector-java(轻量级,易集成)。只需配置好 MySQL、账号和订阅参数,即可在 Java 程序中实时解析 binlog 事件,获取数据变更明细。

创作不易,点点关注!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猩火燎猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值