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 redis.clients.jedis.Jedis;
public class CanalToRedis {
public static void main(String args[]) {
// 创建连接
CanalConnector connector = CanalConnectors.newSingleConnector(
new InetSocketAddress(AddressUtils.getHostIp(),
11111), "example", "", "");
// 启动连接
connector.connect();
connector.subscribe(".*\\..*");
Jedis jedis = new Jedis("localhost");
while (true) {
// 获取数据
Message message = connector.getWithoutAck(1024); // 获取指定数量的数据
long batchId = message.getId();
if (batchId == -1 || message.getEntries().isEmpty()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
dataHandle(message, jedis);
connector.ack(batchId); // 确认消息消费成功
}
}
}
private static void dataHandle(Message message, Jedis jedis) {
for (CanalEntry.Entry entry : message.getEntries()) {
if (entry.getEntryType() == CanalEntry.EntryType.ROWDATA) {
CanalEntry.RowChange rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
if (rowData.getAction() == CanalEntry.EventType.INSERT) {
// 插入数据逻辑
insertData(jedis, entry, rowData);
} else if (rowData.getAction() == CanalEntry.EventType.UPDATE) {
// 更新数据逻辑
updateData(jedis, entry, rowData);
} else if (rowData.getAction() == CanalEntry.EventType.DELETE) {
// 删除数据逻辑
deleteData(jedis, entry, rowData);
}
}
}
}
评论已关闭