import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.Message;
import com.alibaba.otter.canal.protocol.CanalEntry;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import com.google.protobuf.InvalidProtocolBufferException;
public class DataSync {
public static void main(String args[]) {
// 创建连接
CanalConnector connector = CanalConnectors.newSingleConnector(
new InetSocketAddress(AddressUtils.getHostIp(),
11111), "example", "", "");
// 启动连接
try {
connector.connect();
connector.subscribe(".*\\..*");
connector.rollback();
while (true) {
Message message = connector.getWithoutAck(1024); // 获取指定数量的数据
long batchId = message.getId();
if (batchId == -1 || message.getEntries().isEmpty()) {
Thread.sleep(1000);
} else {
dataHandle(message, client); // 进行数据处理
connector.ack(batchId); // 确认消息消费成功
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connector.disconnect();
}
}
private static void dataHandle(Message message, RestHighLevelClient client) throws InvalidProtocolBufferException {
for (CanalEntry.Entry entry : message.getEntries()) {
if (entry.getEntryType() == CanalEntry.EntryType.ROWDATA) {
CanalEntry.RowChange rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
for (CanalEntry.EventType eventType : rowChage.getEventsList()) {
CanalEntry.RowData rowData = rowChage.getRowDatas(0);
processData(client, entry, rowData);
}
}
}
}
private static void processData(RestHighLevelClient client, CanalEntry.Entry entry, CanalEntry.RowData rowData) throws InvalidProtocolB
评论已关闭