Java监听BinLog服务获取Mysql数据库变化

通过监听BinLog,获取指定表的增删改操作

1.打开mysql控制台执行以下,启动log_bin

show variables like '%log_bin%' ;

在这里插入图片描述
如果是OFF则表示未启用
2.pom文件添加依赖

<dependency>
            <groupId>com.github.shyiko</groupId>
            <artifactId>mysql-binlog-connector-java</artifactId>
            <version>0.21.0</version>
 </dependency>

3.然后再看逻辑代码:
实现是在connectMysqlBinLog()方法中的,里面通过data instanceof XXX ,即可查询到执行的增删改什么请求,详细请看代码

    public void run(ApplicationArguments args) {
        //项目启动完成连接bin-log
        new Thread(() -> {
            String binLog = connectMysqlBinLog();
            System.out.println("binLog = " + binLog);
        }).start();
    }

	static String result = "";
	/**
     * 连接mysqlBinLog
     */
    public String connectMysqlBinLog() {
        log.info("监控BinLog服务已启动");
        BinaryLogClient client = new BinaryLogClient("192.168.0.XXX", 3306, "root", "password");
        client.setServerId(100); //和自己之前设置的server-id保持一致,但是我不知道为什么不一致也能成功
        client.registerEventListener(event -> {
            EventData data = event.getData();
            if (data instanceof TableMapEventData) {
                //只要连接的MySQL发生的增删改的操作,则都会进入这里,无论哪个数据库
                TableMapEventData tableMapEventData = (TableMapEventData) data;
                //指定获取到某个数据库的数据,并指定到表,记录表明
                if(tableMapEventData.getDatabase().equals("data_base")){
                    currentTable = tableMapEventData.getTable();
                }
            }
            //表数据发生插入时触发
            if (data instanceof WriteRowsEventData && currentTable != null) {
                WriteRowsEventData writeEventData = (WriteRowsEventData) data;
                //判断发生新增的是否和上面记录的表名一致
                if ("data_table".equals(currentTable)){
                    for (Serializable[] row : writeEventData.getRows()) {
                        if (Arrays.toString(row).contains("SYCreditEvaluate")){
                        	//记录发生新增数据的insert语句
                            log.info(currentTable + "Values inserted: " + Arrays.toString(row));
                            try {
                                String result = convertStringToPerson(Arrays.toString(row));
                                log.info("---->正常获取到表"+ currentTable + "实时进件的决策数据," + result);
                            }catch (Exception e){
                                log.error("---->捕获异常,请查看"+ currentTable + "表在实时获取进件数据时是否发生异常!");
                            }
                            break;
                        }
                    }
                }
                currentTable = null;
            }
        });
        try {
            client.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String convertStringToPerson(String rowString) {
        //可以通过截取到的索引带入方法获取到具体数据
        String[] split = rowString.split(",");
        String creditId = split[1].trim();
        String orderId = split[1].trim();
        System.out.println("creditId = " + creditId);
        System.out.println("orderId = " + orderId);
        return  "";
    }

4.同理可通过以下获取到修改删除等操作

if (data instanceof UpdateRowsEventData) {
    System.out.println("Update:");
    System.out.println(data.toString());
    //表数据发生插入时触发
} else if (data instanceof WriteRowsEventData) {
    System.out.println("Insert:");
    System.out.println(data.toString());
    //表数据发生删除后触发
} else if (data instanceof DeleteRowsEventData) {
    System.out.println("Delete:");
    System.out.println(data.toString());
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 30
    评论
要使用 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 服务,如果连接失败,则等待一段时间再进行重连。在事件监听器中,我们可以处理不同类型的事件,例如插入、更新、删除语句等。
评论 30
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值