Message message = connector.getWithoutAck(BATCH_SIZE);
//获取批量ID
long batchId = message.getId();
//获取批量的数量
int size = message.getEntries().size();
//如果没有数据
if (batchId == -1 || size == 0) {
try {
//线程休眠2秒
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//处理数据为sql
dataHandle(message.getEntries());
}
/设置队列sql语句执行最大值/
if (SQL_QUEUE.size() >= 1) {
executeQueueSql();
}
//进行 batch id 的确认。确认之后,小于等于此 batchId 的 Message 都会被确认。
connector.ack(batchId);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connector.disconnect();
}
System.out.println(“连接canal end”);
}
/**
-
@description: 处理队列里sql
-
@return:
-
@author: ZhouKaiShun
-
@time: 2021/9/15 10:35
*/
public void executeQueueSql() {
int size = SQL_QUEUE.size();
for (int i = 0; i < size; i++) {
String sql = SQL_QUEUE.poll();
this.execute(sql);
}
}
/**
-
@description: 日志数据处理
-
@return:
-
@author: ZhouKaiShun
-
@time: 2021/9/15 10:35
*/
private void dataHandle(List entrys) throws
InvalidProtocolBufferException {
for (Entry entry : entrys) {
if (CanalEntry.EntryType.ROWDATA == entry.getEntryType()) {
CanalEntry.RowChange rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
CanalEntry.EventType eventType = rowChange.getEventType();
if (eventType == CanalEntry.EventType.DELETE) {
saveDeleteSql(entry);
} else if (eventType == CanalEntry.EventType.UPDATE) {
saveUpdateSql(entry);
} else if (eventType == CanalEntry.EventType.INSERT) {
saveInsertSql(entry);
}
}
}
}
/**
-
@description: 处理update语句
-
@return:
-
@author: ZhouKaiShun
-
@time: 2021/9/15 10:35
*/
private void saveUpdateSql(Entry entry) {
try {
CanalEntry.RowChange rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
List<CanalEntry.RowData> rowDatasList = ro