Java binLog日志监听

监听指定的表去做一些处理逻辑,首先是要开启M有SQL的配置,然后再撸代码。

一、Windows下开启MySQL binLog日志

首先要开启MySQL的BinLog 管理

show variables like '%log_bin%';

 

如果发现是OFF,打开mysql文件夹下面的my.ini,修改一下

如果不知道my.ini 在哪里,打开【服务】-> 右击属性

 

拉到最后就可以看见my.ini,然后找到文件后

[mysqld] 下面加

# 开启bin-log
log-bin=mysql-bin          # 开启binlog功能
binlog-format=ROW          # 设置binlog格式
server_id=1                # 设置服务ID号

然后 重启服务,就会发现已经起好了 

二、Java代码示例演示

首先引入Maven包

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

上代码

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson2.JSON;
import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.*;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.controller.websocket.AlarmWebSocket;
import com.ruoyi.web.service.IWidfireDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * mysql bin log 日志监听
 */
@Component
@Slf4j
public class MySQLBinaryLogConfig {


    public static IWidfireDataService widfireDataService;

    @Autowired
    public void setSenderService(IWidfireDataService widfireDataService){
        MySQLBinaryLogConfig.widfireDataService= widfireDataService;
    }


    private static final List<String> TABLE_NAME = ListUtil.of("alart_ai"); //数据库表,需要监听的表


    {
        System.out.println("启动监听:启动中");
        getThread().start();
        System.out.println("启动监听:成功");
    }

    public Thread getThread() {
        BinaryLogClient client = new BinaryLogClient("127.0.0.1", 3306, "root", "123456");
        client.setServerId(1);
        return new Thread(() -> {
            client.registerEventListener(event -> {
                String table =null;
                final EventData data = event.getData();
                if (data instanceof TableMapEventData) {
                    TableMapEventData tableMapEventData = (TableMapEventData) data;
                    String database = tableMapEventData.getDatabase();
                    table = tableMapEventData.getTable();

                    log.info("数据表:{},data:{},database:{}",table,data.toString(),database);
                }else if (data instanceof UpdateRowsEventData) {
                    UpdateRowsEventData tableMapEventData = (UpdateRowsEventData) data;

                    System.out.println("更新:");
                } else if (data instanceof WriteRowsEventData) {
                    System.out.println("添加:");
                } else if (data instanceof DeleteRowsEventData) {
                    System.out.println("删除:");
                }

                if(StringUtils.isNotEmpty(table) && TABLE_NAME.contains(table)){
                    log.info("<<<<<< 收到MySQL binLog 日志推送 >>>>>>>");
                    //开始编写具体的逻辑
                    
                }

            });
            try {
                client.connect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }






}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java监听MySQL的binlog并将其解析为JSON,可以使用以下步骤: 1. 添加MySQL的binlog依赖库:可以使用开源的库如canal-client或者自己编写解析binlog的代码。 2. 创建一个监听器类,实现MySQL的binlog事件接口:BinlogEventListener。该接口定义了处理所有binlog事件的方法。 3. 实现BinlogEventListener接口的方法,解析binlog事件数据并将其转换为JSON格式。 4. 创建一个canal客户端实例,并将之前创建的监听器类添加到canal客户端中。 5. 启动canal客户端,开始监听MySQL的binlog事件。 以下是一个示例代码,使用canal-client库来监听MySQL的binlog事件并将其解析为JSON格式: ```java import java.util.List; import java.net.InetSocketAddress; import com.alibaba.otter.canal.client.CanalConnectors; import com.alibaba.otter.canal.client.CanalConnector; import com.alibaba.otter.canal.protocol.CanalEntry.*; import com.alibaba.otter.canal.protocol.CanalEntry.Column; import com.alibaba.otter.canal.protocol.CanalEntry.RowChange; import com.alibaba.otter.canal.protocol.CanalEntry.RowData; import com.alibaba.otter.canal.protocol.Message; import com.alibaba.fastjson.JSON; public class BinlogListener implements CanalEventListener { public void onEvent(CanalEntry.Entry entry) { if (entry.getEntryType() == EntryType.ROWDATA) { RowChange rowChange = null; try { ByteString byteString = entry.getStoreValue(); rowChange = RowChange.parseFrom(byteString); } catch (Exception e) { throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(), e); } EventType eventType = rowChange.getEventType(); for (RowData rowData : rowChange.getRowDatasList()) { if (eventType == EventType.DELETE) { printJson(rowData.getBeforeColumnsList()); } else if (eventType == EventType.INSERT) { printJson(rowData.getAfterColumnsList()); } else { printJson(rowData.getAfterColumnsList()); } } } } private void printJson(List<Column> columns) { System.out.println(JSON.toJSONString(columns)); } public static void main(String args[]) { String destination = "example"; String ip = "127.0.0.1"; int port = 11111; String username = ""; String password = ""; CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(ip, port), destination, username, password); BinlogListener listener = new BinlogListener(); connector.connect(); connector.subscribe(".*\\..*"); connector.rollback(); while (true) { Message message = connector.getWithoutAck(1024); // 获取指定数量的数据 long batchId = message.getId(); int size = message.getEntries().size(); if (batchId == -1 || size == 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } else { listener.onEvent(message.getEntries().get(0)); connector.ack(batchId); // 提交确认 } } } } ``` 这个示例代码中使用的canal-client库是由阿里巴巴开源的,可以在maven中心库中找到。其中binlog解析的过程在onEvent方法中,其中解析出的数据都被转换成了JSON格式。可以根据需要将其发送到其他服务进行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值