1. Canal 与 Elasticsearch 实时同步概述
Canal 是阿里巴巴开源的基于数据库增量日志解析的组件,支持 MySQL、Oracle 等数据库。它通过解析数据库的 binlog 日志,将数据变更事件推送到消息队列或直接处理,实现数据的准实时同步。Elasticsearch 是一个基于 Lucene 库的搜索引擎,具有强大的全文检索和分析能力。
将 Canal 与 Elasticsearch 结合使用,可以实现数据库数据到 Elasticsearch 的准实时同步,充分发挥 Elasticsearch 在搜索、分析和日志处理方面的优势。这种架构广泛应用于电商搜索、日志分析、监控告警等场景。
Canal 与 Elasticsearch 同步的基本架构包括:
- Canal Server: 监听并解析数据库 binlog
- Canal Client: 接收变更事件并处理
- 数据转换: 将数据库数据转换为 Elasticsearch 文档格式
- Elasticsearch Indexer: 将文档写入 Elasticsearch
这种架构的优势在于低延迟、高可靠性,且对数据库几乎无侵入。
2. 增量索引更新实现
增量索引更新是同步方案的核心,主要通过 Canal 监听数据库变更事件,并将变更应用到 Elasticsearch 索引中。
实现增量更新的关键步骤:
2.1. 配置 Canal 监听数据库
首先需要在 MySQL 数据库中开启 binlog 功能,并配置 Canal 监听指定数据库。修改 my.cnf 文件,添加以下配置:
[mysqld]
server-id=1
log-bin=mysql-bin
binlog-format=ROW
binlog-row-image=FULL
2.2. 创建 Canal 实例
创建一个新的 Canal 实例,指向需要同步的数据库:
canal.instance.mysql.slaveId=1234
canal.instance.dbUsername=canal
canal.instance.dbPassword=canal
canal.instance.dbName=your_database
canal.instance.dbEncoding=UTF-8
2.3. 实现消息处理逻辑
编写 Canal Client 接收变更事件,并将数据写入 Elasticsearch:
java
public class ElasticsearchHandler implements EntryHandler<CanalEntry.Entry> {
private RestHighLevelClient esClient;
public ElasticsearchHandler(RestHighLevelClient esClient) {
this.esClient = esClient;
}
@Override
public void handle(CanalEntry.Entry entry) throws Exception {
if (entry.getEntryType() == CanalEntry.EntryType.ROWDATA) {
CanalEntry.RowChange rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
if (rowChange.getEventType() == CanalEntry.EventType.INSERT ||
rowChange.getEventType() == CanalEntry.EventType.UPDATE) {
// 处理插入和更新操作
IndexRequest request = new IndexRequest("your_index")
.id(rowData.getAfterColumns(0).getValue())
.source(convertToMap(rowData.getAfterColumnsList()));
esClient.index(request, RequestOptions.DEFAULT);
} else if (rowChange.getEventType() == CanalEntry.EventType.DELETE) {
// 处理删除操作
DeleteRequest request = new DeleteRequest("your_index")
.id(rowData.getBeforeColumns(0).getValue());
esClient.delete(request, RequestOptions.DEFAULT);
}
}
}
}
private Map<String, Object> convertToMap(List<CanalEntry.Column> columns) {
Map<String, Object> map = new HashMap<>();
for (CanalEntry.Column column : columns) {
if (column.getIsNull()) {
map.put(column.getName(), null);
} else {
map.put(column.getName(), column.getValue());
}
}
return map;
}
}
2.4. 处理批量提交
为提高性能,可以使用批量提交机制:
java
BulkRequest bulkRequest = new BulkRequest();
// 添加多个索引/删除请求到批量请求中
// ...
// 执行批量提交
BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
if (bulkResponse.hasFailures()) {
// 处理失败情况
}
3. 数据删除处理方案
在 Canal 与 Elasticsearch 同步过程中,处理删除操作是一个关键点。与数据更新不同,删除操作需要特别注意数据一致性和同步延迟问题。
3.1. 基于主键的删除处理
最简单的删除方式是基于主键进行删除,如上述代码所示。这种方法适用于每个表都有明确主键的情况。
3.2. 软删除与硬删除
根据业务需求,可以选择软删除或硬删除:
- 硬删除:直接从 Elasticsearch 中删除文档
- 软删除:在文档中标记为已删除,而不是真正删除,适合需要保留历史数据的场景
3.3. 删除事件过滤
在某些场景下,可能需要过滤特定的删除事件:
java
@Override
public void handle(CanalEntry.Entry entry) throws Exception {
if (entry.getEntryType() == CanalEntry.EntryType.ROWDATA) {
CanalEntry.RowChange rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
if (rowChange.getEventType() == CanalEntry.EventType.DELETE) {
// 检查是否需要跳过此删除事件
if (shouldSkipDelete(rowData)) {
continue;
}
// 执行删除操作
DeleteRequest request = new DeleteRequest("your_index")
.id(rowData.getBeforeColumns(0).getValue());
esClient.delete(request, RequestOptions.DEFAULT);
}
}
}
}
private boolean shouldSkipDelete(CanalEntry.RowData rowData) {
// 根据业务逻辑判断是否跳过删除
// 例如:特定状态的数据不执行删除操作
for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
if ("status".equals(column.getName()) && "inactive".equals(column.getValue())) {
return true;
}
}
return false;
}
3.4. 删除操作的幂等性
确保删除操作的幂等性非常重要,特别是在网络不稳定或重试的情况下:
java
public void safeDelete(String index, String id) {
try {
// 检查文档是否存在
GetRequest getRequest = new GetRequest(index, id);
boolean exists = esClient.exists(getRequest, RequestOptions.DEFAULT);
if (exists) {
// 文档存在则删除
DeleteRequest deleteRequest = new DeleteRequest(index, id);
esClient.delete(deleteRequest, RequestOptions.DEFAULT);
}
// 如果文档不存在,不做任何操作
} catch (ElasticsearchException e) {
// 处理异常,如文档已被其他线程删除的情况
if (e.getDetailedMessage().contains("missing")) {
// 文档不存在,无需处理
return;
}
throw e;
}
}
4. 全量重建策略
虽然增量同步能够保持数据一致性,但在某些情况下需要进行全量重建,例如:
- 首次同步
- 索引结构变更
- 数据发生严重不一致需要修复
4.1. 全量重建方案设计
全量重建的基本流程如下:
- 停止 Canal 增量同步
- 从数据库导出全量数据
- 清空 Elasticsearch 索引
- 将全量数据导入 Elasticsearch
- 重新启动 Canal 增量同步
4.2. 实现全量数据导出
可以使用 JDBC 直接从数据库查询全量数据:
java
public List<Map<String, Object>> exportFullData(String sql, Connection connection) throws SQLException {
List<Map<String, Object>> result = new ArrayList<>();
try (PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
while (rs.next()) {
Map<String, Object> row = new LinkedHashMap<>();
for (int i = 1; i <= columnCount; i++) {
row.put(metaData.getColumnName(i), rs.getObject(i));
}
result.add(row);
}
}
return result;
}
4.3. 批量导入 Elasticsearch
使用 Elasticsearch 的批量 API 高效导入数据:
java
public void bulkIndexToES(List<Map<String, Object>> documents, String index) throws IOException {
BulkRequest bulkRequest = new BulkRequest();
for (Map<String, Object> doc : documents) {
// 假设文档中包含 id 字段
String id = doc.get("id").toString();
// 移除 id 字段,因为它在 IndexRequest 中单独指定
doc.remove("id");
IndexRequest request = new IndexRequest(index).id(id).source(doc);
bulkRequest.add(request);
// 每 1000 条提交一次
if (bulkRequest.numberOfActions() == 1000) {
BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
if (bulkResponse.hasFailures()) {
// 处理失败
handleFailures(bulkResponse);
}
bulkRequest = new BulkRequest();
}
}
// 提交剩余的请求
if (bulkRequest.numberOfActions() > 0) {
BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
if (bulkResponse.hasFailures()) {
handleFailures(bulkResponse);
}
}
}
private void handleFailures(BulkResponse bulkResponse) {
for (BulkItemResponse response : bulkResponse) {
if (response.isFailed()) {
// 记录失败信息
System.err.println("Failed to process document: " + response.getId()
+ ", Error: " + response.getFailure().getMessage());
}
}
}
4.4. 全量重建与增量同步的衔接
为避免数据丢失,全量重建与增量同步之间需要正确衔接:
- 记录全量数据导出的时间点 T
- 在时间点 T 之后的所有数据库变更需要单独记录
- 全量数据导入完成后,将时间点 T 之后的增量变更同步到 Elasticsearch
这可以通过记录 binlog 位置来实现:
java
public class BinlogPosition {
private String logFileName;
private long logFileOffset;
// 获取方法
public String getLogFileName() { return logFileName; }
public long getLogFileOffset() { return logFileOffset; }
// 设置方法
public void setLogFileName(String logFileName) { this.logFileName = logFileName; }
public void setLogFileOffset(long logFileOffset) { this.logFileOffset = logFileOffset; }
}
// 在全量导出开始前记录位置
public BinlogPosition getCurrentBinlogPosition(Connection mysqlConn) throws SQLException {
BinlogPosition position = new BinlogPosition();
try (Statement stmt = mysqlConn.createStatement();
ResultSet rs = stmt.executeQuery("SHOW MASTER STATUS")) {
if (rs.next()) {
position.setLogFileName(rs.getString("File"));
position.setLogFileOffset(rs.getLong("Position"));
}
}
return position;
}
// 在全量导入完成后从此位置继续同步
public void resumeIncrementalSync(BinlogPosition position) {
// 配置 Canal 从指定位置开始监听
canalConfig.setMasterId(position.getLogFileName());
canalConfig.setSlaveId(position.getLogFileOffset());
// 启动 Canal 客户端
startCanalClient();
}
5. 实践案例与注意事项
5.1. 完整的最小示例
下面是一个完整的 Canal 与 Elasticsearch 同步的最小示例:
java
public class CanalElasticsearchSync {
private RestHighLevelClient esClient;
private CanalClient canalClient;
public void init() {
// 初始化 Elasticsearch 客户端
esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 初始化 Canal 客户端
canalClient = new CanalConnector("localhost", 11111, "canal", "canal", "example");
canalClient.connect();
canalClient.subscribe();
canalClient.rollback();
}
public void startSync() {
try {
while (true) {
Message message = canalClient.getWithoutAck(100);
long batchId = message.getId();
if (message.getEntries() != null && !message.getEntries().isEmpty()) {
for (CanalEntry.Entry entry : message.getEntries()) {
handleEntry(entry);
}
}
canalClient.ack(batchId);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
canalClient.disconnect();
try {
esClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handleEntry(CanalEntry.Entry entry) throws Exception {
if (entry.getEntryType() == CanalEntry.EntryType.ROWDATA) {
CanalEntry.RowChange rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
if (rowChange.getEventType() == CanalEntry.EventType.INSERT ||
rowChange.getEventType() == CanalEntry.EventType.UPDATE) {
// 处理插入和更新
IndexRequest request = new IndexRequest("your_index")
.id(rowData.getAfterColumns(0).getValue())
.source(convertColumnsToMap(rowData.getAfterColumnsList()));
esClient.index(request, RequestOptions.DEFAULT);
} else if (rowChange.getEventType() == CanalEntry.EventType.DELETE) {
// 处理删除
DeleteRequest request = new DeleteRequest("your_index")
.id(rowData.getBeforeColumns(0).getValue());
esClient.delete(request, RequestOptions.DEFAULT);
}
}
}
}
private Map<String, Object> convertColumnsToMap(List<CanalEntry.Column> columns) {
Map<String, Object> map = new HashMap<>();
for (CanalEntry.Column column : columns) {
if (column.getIsNull()) {
map.put(column.getName(), null);
} else {
map.put(column.getName(), column.getValue());
}
}
return map;
}
public static void main(String[] args) {
CanalElasticsearchSync sync = new CanalElasticsearchSync();
sync.init();
sync.startSync();
}
}
5.2. 注意事项
- 性能监控:监控 Canal 和 Elasticsearch 的性能指标,及时发现并处理性能瓶颈
- 错误处理:建立完善的错误处理机制,特别是网络中断、数据格式错误等情况
- 数据一致性:定期检查 Canal 和 Elasticsearch 之间的数据一致性,特别是关键业务数据
- 备份策略:制定并执行数据备份策略,防止数据丢失
- 版本兼容性:确保 Canal 和 Elasticsearch 版本兼容,避免因版本不匹配导致的问题
- 资源管理:合理配置内存和线程资源,避免资源耗尽导致系统崩溃
5.3. 同步策略对比
| 同步策略 | 优点 | 缺点 | 适用场景 |
|---------|------|------|---------|
| 实时同步 | 低延迟,数据最新 | 对数据库压力大,资源消耗高 | 对实时性要求高的场景 |
| 批量同步 | 资源消耗小,系统稳定性高 | 同步延迟高 | 对实时性要求不高的场景 |
| 混合策略 | 平衡实时性与资源消耗 | 实现复杂度高 | 大规模数据同步场景 |
下面是 Canal 与 Elasticsearch 实时同步的流程图:
#publish-mermaid-1788488686886-0{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#publish-mermaid-1788488686886-0 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1788488686886-0 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1788488686886-0 .error-icon{fill:#552222;}#publish-mermaid-1788488686886-0 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1788488686886-0 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1788488686886-0 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1788488686886-0 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1788488686886-0 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1788488686886-0 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1788488686886-0 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1788488686886-0 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1788488686886-0 .marker.cross{stroke:#333333;}#publish-mermaid-1788488686886-0 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1788488686886-0 p{margin:0;}#publish-mermaid-1788488686886-0 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#publish-mermaid-1788488686886-0 .cluster-label text{fill:#333;}#publish-mermaid-1788488686886-0 .cluster-label span{color:#333;}#publish-mermaid-1788488686886-0 .cluster-label span p{background-color:transparent;}#publish-mermaid-1788488686886-0 .label text,#publish-mermaid-1788488686886-0 span{fill:#333;color:#333;}#publish-mermaid-1788488686886-0 .node rect,#publish-mermaid-1788488686886-0 .node circle,#publish-mermaid-1788488686886-0 .node ellipse,#publish-mermaid-1788488686886-0 .node polygon,#publish-mermaid-1788488686886-0 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1788488686886-0 .rough-node .label text,#publish-mermaid-1788488686886-0 .node .label text,#publish-mermaid-1788488686886-0 .image-shape .label,#publish-mermaid-1788488686886-0 .icon-shape .label{text-anchor:middle;}#publish-mermaid-1788488686886-0 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#publish-mermaid-1788488686886-0 .rough-node .label,#publish-mermaid-1788488686886-0 .node .label,#publish-mermaid-1788488686886-0 .image-shape .label,#publish-mermaid-1788488686886-0 .icon-shape .label{text-align:center;}#publish-mermaid-1788488686886-0 .node.clickable{cursor:pointer;}#publish-mermaid-1788488686886-0 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#publish-mermaid-1788488686886-0 .arrowheadPath{fill:#333333;}#publish-mermaid-1788488686886-0 .edgePath .path{stroke:#333333;stroke-width:1px;}#publish-mermaid-1788488686886-0 .flowchart-link{stroke:#333333;fill:none;}#publish-mermaid-1788488686886-0 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1788488686886-0 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#publish-mermaid-1788488686886-0 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1788488686886-0 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#publish-mermaid-1788488686886-0 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#publish-mermaid-1788488686886-0 .cluster text{fill:#333;}#publish-mermaid-1788488686886-0 .cluster span{color:#333;}#publish-mermaid-1788488686886-0 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#publish-mermaid-1788488686886-0 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#publish-mermaid-1788488686886-0 rect.text{fill:none;stroke-width:0;}#publish-mermaid-1788488686886-0 .icon-shape,#publish-mermaid-1788488686886-0 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1788488686886-0 .icon-shape p,#publish-mermaid-1788488686886-0 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#publish-mermaid-1788488686886-0 .icon-shape .label rect,#publish-mermaid-1788488686886-0 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1788488686886-0 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#publish-mermaid-1788488686886-0 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#publish-mermaid-1788488686886-0 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1788488686886-0 data-look="neo".node rect,#publish-mermaid-1788488686886-0 data-look="neo".cluster rect,#publish-mermaid-1788488686886-0 data-look="neo".node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1788488686886-0 data-look="neo".swimlane.cluster rect{filter:none;}#publish-mermaid-1788488686886-0 data-look="neo".node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1788488686886-0 data-look="neo".node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1788488686886-0 data-look="neo".node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1788488686886-0 data-look="neo".node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1788488686886-0 data-look="neo".node circle .state-start{fill:#000000;}#publish-mermaid-1788488686886-0 data-look="neo".icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1788488686886-0 data-look="neo".icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1788488686886-0 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} Binlog 变更数据 处理数据 监控 监控 监控 MySQL数据库
Canal服务器
消息队列/处理程序
Elasticsearch
监控工具