最近發現一個挺不錯的框架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的元數據。
