java读取mysql的binlog日志

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.github.shyiko.mysql.binlog.BinaryLogFileReader;
import com.github.shyiko.mysql.binlog.event.Event;
import com.github.shyiko.mysql.binlog.event.deserialization.ChecksumType;
import com.github.shyiko.mysql.binlog.event.deserialization.EventDeserializer;

class Sample {
	public static void main(String[] args) throws IOException {
		String filePath = "D:\\mysql-bin.000345";
		File binlogFile = new File(filePath);
		EventDeserializer eventDeserializer = new EventDeserializer();
		eventDeserializer.setChecksumType(ChecksumType.CRC32);
		BinaryLogFileReader reader = new BinaryLogFileReader(binlogFile,
				eventDeserializer);
		try {
			// 准备写入的文件名称
			/*
			 * File f1 = new File("D:\\mysql-bin.000845.sql"); if
			 * (f1.exists()==false){ f1.getParentFile().mkdirs(); }
			 */
			FileOutputStream fos = new FileOutputStream(
					"D:\\mysql-bin.000345.sql", true);
			for (Event event; (event = reader.readEvent()) != null;) {
				System.out.println(event.toString());

				// 把数据写入到输出流
				fos.write(event.toString().getBytes());
			}
			// 关闭输出流
			fos.close();
			System.out.println("输入完成");
		} finally {
			reader.close();
		}

	}
}

然后在pom中配置如下依赖的jar包

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

猜你喜欢

转载自blog.csdn.net/ystyaoshengting/article/details/82869335