最近发现一个挺不错的框架mysql-binlog-connector-java,可以实时监控binlog的变化。

首先检查mysql的binlog是否开启,在开启的情况下:

引入依赖

1
2
3
4
5
  <dependency>
    <groupId>com.github.shyiko</groupId>
    <artifactId>mysql-binlog-connector-java</artifactId>
    <version>0.18.1</version>
</dependency>

 然后使用如下代码可以测试:        

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class App
{
    public static void main( String[] args ) throws IOException
    {
        BinaryLogClient client = new BinaryLogClient("xxx", 3306, "xxx", "xxx");
        EventDeserializer eventDeserializer = new EventDeserializer();
        eventDeserializer.setCompatibilityMode(
            EventDeserializer.CompatibilityMode.DATE_AND_TIME_AS_LONG,
            EventDeserializer.CompatibilityMode.CHAR_AND_BINARY_AS_BYTE_ARRAY
        );
        client.setEventDeserializer(eventDeserializer);
        client.registerEventListener(new EventListener() {
 
            @Override
            public void onEvent(Event event) {
                    System.out.println(event);
                    EventData data = event.getData();
                  
                    if (data instanceof UpdateRowsEventData) {
                        System.out.println("Update--------------");
                        System.out.println(data.toString());
                    } else if (data instanceof WriteRowsEventData) {
                        System.out.println("Write---------------");
                        System.out.println(data.toString());
                    } else if (data instanceof DeleteRowsEventData) {
                        System.out.println("Delete--------------");
                        System.out.println(data.toString());
                    }
            }
        });
        client.connect();
    }
}                                                                                                                                                <br><br>实际在使用的时候,这个框架提供列名称表名称不太好用,这个时候需要<a href="https://github.com/ngocdaothanh/mydit" rel="noopener nofollow">https://github.com/ngocdaothanh/mydit</a> ,这个是一个将mysql同步到mongdb的,其中一些样例代码可以很方便的获取mysql的元数据。