最近发现一个挺不错的框架mysql-binlog-connector-java,可以实时监控binlog的变化。
首先检查mysql的binlog是否开启,在开启的情况下:
引入依赖
<dependency> <groupId>com.github.shyiko</groupId> <artifactId>mysql-binlog-connector-java</artifactId> <version>0.18.1</version> </dependency>
然后使用如下代码可以测试:
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(); } }
实际在使用的时候,这个框架提供列名称表名称不太好用,这个时候需要https://github.com/ngocdaothanh/mydit ,这个是一个将mysql同步到mongdb的,其中一些样例代码可以很方便的获取mysql的元数据。