监听MySQL binlog

背景

1、内容

通过监听mysql的主库的写、删、更新操作产生的binlog日志,来做业务(eg:监控数据、同步数据等)

2、作用

  • 无感知

服务A编辑数据库,服务B监听A的mysql内容,对于A而言,感知不到服务B的存在

3、缺点

  • 主库压力大

如果写的并发很高,服务B监听binlog,同步信息,会对主库造成压力

  • 必须写库成功后,才能监听到binlog同步的内容

假如B站用户点赞行为,A服务需要写库,写完库后,B服务需要同步财务结算up主收益

假如A写库失败了,B服务监听不到binlog,本次点赞行为就丢失了。这种场景不适合

这种场景可以使用MQ来解决


快速入门

1、pom

<!-- https://mvnrepository.com/artifact/com.gitee.Jmysy/binlog4j-spring-boot-starter -->
<dependency>
    <groupId>com.gitee.Jmysy</groupId>
    <artifactId>binlog4j-spring-boot-starter</artifactId>
    <version>1.9.1</version>
</dependency>
  • 支持集群模式
  • 宕机续读(服务A写mysql,服务B监听,假如在服务B宕机期间,A写了新数据,则B重新启动后,仍可以获取到期间的binlog同步内容),实现:通过redis配置的serverId,去对应的binlogfileName + position获取
  • 数据转换

2、yml配置

spring:
  binlog4j:
    redis-config:
      host: 127.0.0.1
      port: 6379
      database: 1
    client-configs:
      master:
        host: "127.0.0.1"
        port: 3306
        username: "root"
        password: "941123"
        mode: standalone
        persistence: true
        server-id: 1234

2、code实现

package com.mjp.binlog;

import com.gitee.Jmysy.binlog4j.core.BinlogEvent;
import com.gitee.Jmysy.binlog4j.core.IBinlogEventHandler;
import com.gitee.Jmysy.binlog4j.springboot.starter.annotation.BinlogSubscriber;

/**
 * Author:majinpeng
 * Date: 2024/08/23 10:47
 */
@BinlogSubscriber(clientName = "master")
public class Binlog4jServiceHandler implements IBinlogEventHandler<Object> {
    // 这里的Object即你数据库中的实体类,比如Order、User
    // 如果可以确定,则使用具体的User
    // 如果是Object,则binlogEvent中的T data属性是map
    @Override
    public void onInsert(BinlogEvent<Object> binlogEvent) {

    }

    @Override
    public void onUpdate(BinlogEvent<Object> binlogEvent) {
        System.out.println(binlogEvent.toString());
    }

    @Override
    public void onDelete(BinlogEvent<Object> binlogEvent) {

    }

    @Override
    public boolean isHandle(String s, String s1) {
        // 如果将<Object>使用具体的<User>接收,则一定需要在isHandle中,判断当前Binlog4jServiceHandler是否执行了
        // 否则可能会因为映射的对象不符合,造成数据丢失
        return false;
    }
}

监听普通文件内容变动

1、实现CommandLineRunner接口 或 ApplicationRunner接口

2、使用hutool的WatchMonitor工具类(底层封装了JDK的WatchService)

<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.31</version>
</dependency>

3、使用Tailer工具类

@Component
public class MonitorFile implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        File file = FileUtil.file("C:\\Users\\admin\\Desktop\\test.txt");
        try (WatchMonitor watchMonitor = WatchMonitor.create(file, WatchMonitor.ENTRY_MODIFY)) {
            watchMonitor.setWatcher(new Watcher() {
                @Override
                public void onCreate(WatchEvent<?> event, Path currentPath) {

                }

                @Override
                public void onModify(WatchEvent<?> event, Path currentPath) {
                    Object context = event.context();
                    System.out.println("modify!!!" + context.toString());
                }

                @Override
                public void onDelete(WatchEvent<?> event, Path currentPath) {

                }

                @Override
                public void onOverflow(WatchEvent<?> event, Path currentPath) {

                }
            });
            // 监听目录的足最大深度,
            watchMonitor.setMaxDepth(3);
            watchMonitor.start();
        }

        Tailer tailer = new Tailer(file, line -> System.out.println("变动的数据内容为:" + line));
        tailer.start();
    }
}
要使用 Java 代码监听 MySQL binlog,可以使用 MySQL Connector/J 驱动程序提供的 API。以下是一个简单的示例代码: ```java import java.io.IOException; import java.io.Serializable; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.mysql.cj.jdbc.MysqlDataSource; import com.mysql.cj.jdbc.exceptions.CommunicationsException; import com.mysql.cj.jdbc.exceptions.MySQLTimeoutException; import com.mysql.cj.jdbc.exceptions.PacketTooBigException; import com.mysql.cj.jdbc.exceptions.WrongArgumentException; import com.mysql.cj.jdbc.exceptions.WrongUsageException; import com.mysql.cj.protocol.ResultsetRow; import com.mysql.cj.protocol.a.BinaryRowDecoder; import com.mysql.cj.protocol.a.MysqlBinaryLogClient; import com.mysql.cj.result.Row; import com.mysql.cj.result.RowList; public class MySQLBinlogListener { private final String host; private final int port; private final String username; private final String password; private final String schemaName; private final long serverId; private final long binlogPosition; private final String binlogFilename; public MySQLBinlogListener(String host, int port, String username, String password, String schemaName, long serverId, long binlogPosition, String binlogFilename) { this.host = host; this.port = port; this.username = username; this.password = password; this.schemaName = schemaName; this.serverId = serverId; this.binlogPosition = binlogPosition; this.binlogFilename = binlogFilename; } public void start() throws SQLException, IOException { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setServerName(host); dataSource.setPort(port); dataSource.setUser(username); dataSource.setPassword(password); dataSource.setDatabaseName(schemaName); Connection connection = DriverManager.getConnection(dataSource.getUrl(), dataSource.getUser(), dataSource.getPassword()); connection.setAutoCommit(false); MysqlBinaryLogClient client = new MysqlBinaryLogClient(host, port, username, password); client.setServerId(serverId); client.setBinlogFilename(binlogFilename); client.setBinlogPosition(binlogPosition); client.registerEventListener(event -> { if (event.getData() instanceof RowList) { RowList rows = (RowList) event.getData(); List<Serializable[]> rowDataList = new ArrayList<>(); for (Row row : rows) { BinaryRowDecoder decoder = new BinaryRowDecoder(rows.getColumnTypes(), row); Serializable[] rowData = decoder.decode(); rowDataList.add(rowData); } // 处理 rowDataList 中的数据 System.out.println("Received " + rowDataList.size() + " rows"); } else if (event.getData() instanceof ResultsetRow) { ResultsetRow row = (ResultsetRow) event.getData(); BinaryRowDecoder decoder = new BinaryRowDecoder(event.getColumnTypes(), row); Serializable[] rowData = decoder.decode(); // 处理 rowData 中的数据 System.out.println("Received 1 row"); } else { // 处理其他类型的事件(例如DDL语句) System.out.println("Received other event"); } }); while (true) { try { client.connect(); } catch (WrongArgumentException | WrongUsageException | PacketTooBigException e) { // 处理异常 } catch (MySQLTimeoutException | CommunicationsException e) { // 处理异常 } Thread.sleep(1000); } } } ``` 在这个示例代码中,我们使用 `MysqlBinaryLogClient` 类来连接 MySQL 服务器,并使用 `registerEventListener` 方法注册一个事件监听器。当有新的 binlog 事件产生时,事件监听器会被触发,我们可以在事件监听器中处理事件的数据。 要启动监听程序,只需要创建一个 `MySQLBinlogListener` 对象,并调用 `start` 方法即可。在 `start` 方法中,我们创建了一个 `MysqlDataSource` 对象来连接 MySQL 数据库,并创建了一个 `MysqlBinaryLogClient` 对象来连接 binlog 服务。然后,我们使用一个无限循环来不断连接 binlog 服务,如果连接失败,则等待一段时间再进行重连。在事件监听器中,我们可以处理不同类型的事件,例如插入、更新、删除语句等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值