引入pom
<dependency>
<groupId>com.zendesk</groupId>
<artifactId>mysql-binlog-connector-java</artifactId>
<version>0.28.0</version>
</dependency>
加入配置
mysql-binlog-connect-java:
datasource:
hostname: 127.0.0.1
port: 3306
username: 用户名
password: 密码
schema: 需要监听的数据库名称
增加配置文件
@EnableConfigurationProperties({MySqlBinlogConnectJavaProperties.class})
@Configuration
@ConditionalOnProperty("mysql-binlog-connect-java.datasource.hostname")
@AllArgsConstructor
@Slf4j
public class BinLogConfig {
private final MySqlBinlogConnectJavaProperties mySqlBinlogConnectJavaProperties;
private final Map<Long,String> eventTableMap = new HashMap<>();
@PostConstruct
public void init() throws IOException {
try {
List<Class<?>> NORMAL_TYPE = Lists.newArrayList(byte.class, Byte.class,
short.class, Short.class,
int.class, Integer.class,
long.class, Long.class,
float.class, Float.class,
double.class, Double.class,
char.class, Character.class,
String.class,
BigDecimal.class);
String hostname = mySqlBinlogConnectJavaProperties.getHostname();
String schema = mySqlBinlogConnectJavaProperties.getSchema();
Integer port = mySqlBinlogConnectJavaProperties.getPort();
String username = mySqlBinlogConnectJavaProperties.getUsername();
String password = mySqlBinlogConnectJavaProperties.getPassword();
// 配置客户端连接
BinaryLogClient client = new BinaryLogClient(hostname, port, username, password);
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(event -> {
EventHeaderV4 header = event.getHeader();
EventType eventType = header.getEventType();
if(eventType == EventType.TABLE_MAP ){
//执行更新时会先收到一个表格map事件,这里缓存下来后面表格更新事件来的时候可以做判定
EventData data = event.getData();
TableMapEventData tableMapEventData = (TableMapEventData)data;
eventTableMap.put(tableMapEventData.getTableId(),tableMapEventData.getTable());
}
if (eventType == EventType.EXT_UPDATE_ROWS) {
EventData data = event.getData();
if (data instanceof UpdateRowsEventData) {
UpdateRowsEventData eventData = (UpdateRowsEventData) data;
long tableId = eventData.getTableId();
String s = eventTableMap.get(tableId);
if(!"监听的数据库表名".equals(s)){
//非目的关注表直接返回
return;
}
for (Map.Entry<Serializable[], Serializable[]> row : eventData.getRows()) {
Integer dbId = (Integer)(row.getValue()[0]);
BitSet includedColumns = eventData.getIncludedColumns();
if(includedColumns == null || includedColumns.isEmpty()){
return ;
}
String 新数据值 = new String((byte[])(row.getValue()[1]) ) ;
String newDbStatusField = new String((byte[])(row.getValue()[statusColIndex]) ) ;
String 旧数据值 = new String((byte[])(row.getKey()[statusColIndex]) ) ;
}
}
}
}
});
client.connect();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}