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 CanalRedisSync {
public static void main(String args[]) {
// 创建连接
CanalConnector connector = CanalConnectors.newSingleConnector(
new InetSocketAddress(AddressUtils.getHostIp(),
11111), "example", "", "");
// 启动连接
try {
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.getEntries(), jedis);
connector.ack(batchId); // 确认数据消费成功
}
}
} finally {
connector.disconnect();
}
}
private static void dataHandle(List<CanalEntry.Entry> entrys, Jedis jedis) {
for (CanalEntry.Entry entry : entrys) {
if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
// 开始事务或者结束事务
} else if (entry.getEntryType() == CanalEntry.EntryType.ROWDATA) {
// 数据变更事件
CanalEntry.RowChange rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
if (rowChage.getEventType() == CanalEntry.EventType.INSERT) {
// 插入操作
// 将数据同步到Redis
jedis.set(rowData.getBeforeColumnsList().get(0).getName(), rowData.getAfterColumnsList().get(0).getValue());
} else if (rowChage.getEventType() ==
评论已关闭