canal实现MySQL和ES同步实践
以下是一个简化的示例,展示了如何使用Canal将MySQL数据变化同步到Elasticsearch。
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 org.springframework.stereotype.Component;
@Component
public class DataSyncToES {
private final RestHighLevelClient client;
public DataSyncToES(RestHighLevelClient client) {
this.client = client;
}
public void sync() {
CanalConnector connector = CanalConnectors.newSingleConnector(
new InetSocketAddress(AddressUtils.getHostIp(),
11111), "example", "", "");
int batchSize = 1000;
try {
connector.connect();
connector.subscribe(".*\\..*");
connector.rollback();
while (true) {
Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
long batchId = message.getId();
if (batchId == -1 || message.getEntries().isEmpty()) {
Thread.sleep(1000);
} else {
dataHandler(message.getEntries());
connector.ack(batchId); // 确认消息消费成功
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connector.disconnect();
}
}
private void dataHandler(List<CanalEntry.Entry> entrys) throws IOException {
for (CanalEntry.Entry entry : entrys) {
if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
continue;
}
CanalEntry.RowChange rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
String tableName = entry.getHeader().getTableName();
for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
if (rowData.getEventType() == CanalEntry.EventType.DELETE) {
// 处理删除事件
} else if (rowData.getEventType() == CanalEntry.EventType.INSERT) {
// 处理插入事件
IndexRequest request = new Ind
评论已关闭