提交工单

MySQL Binlog实时数据同步:CDC变更数据捕获与ElasticSearch/Redis同步实战

传统双写(写MySQL的同时写ES/Redis)存在一致性风险——两个写操作之间可能有一个失败。CDC(Change Data Capture)通过监听MySQL的Binlog日志,以事后同步的方式保证最终一致性,是数据同步的工业级方案。

一、CDC原理

<code">MySQL主从复制的原理是Binlog,Canal伪装成MySQL从库:

用户写入MySQL → MySQL记录Binlog
                    ↓
            Canal伪装成从库读取Binlog
                    ↓
          解析Binlog中的数据变更(INSERT/UPDATE/DELETE)
                    ↓
    ┌───────────────────────────────────┐
    ├→ 同步到ElasticSearch(全文搜索)   │
    ├→ 更新Redis缓存(失效或更新)       │
    ├→ 发送到Kafka(事件驱动其他服务)  │
    └→ 同步到数据仓库(ClickHouse分析) │
    └───────────────────────────────────┘

二、MySQL Binlog配置

<code"># /etc/mysql/mysql.conf.d/mysqld.cnf

# 开启Binlog(CDC必须项)
server-id = 1
log-bin = /var/log/mysql/mysql-bin.log
binlog-format = ROW       # ROW格式记录每行变更(CDC必须)
binlog-row-image = FULL   # 记录修改前后的完整行数据

# Binlog保留时间
binlog-expire-logs-seconds = 604800  # 7天

# 数据库级别过滤(只记录需要同步的库)
binlog-do-db = shop_db

systemctl restart mysql
<code"># 为Canal创建专用的MySQL账号
mysql -u root -p << 'SQL'
CREATE USER 'canal'@'%' IDENTIFIED BY 'canal密码';
GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'canal'@'%';
FLUSH PRIVILEGES;
SQL

# 验证Binlog已开启
mysql -u root -p -e "SHOW VARIABLES LIKE 'log_bin%';"
# log_bin = ON ← 必须

三、Canal安装配置

<code"># 下载Canal(阿里开源的MySQL Binlog解析工具)
mkdir -p /srv/canal && cd /srv/canal
wget https://github.com/alibaba/canal/releases/download/canal-1.1.7/canal.deployer-1.1.7.tar.gz
tar xzf canal.deployer-1.1.7.tar.gz
<code"># conf/example/instance.properties
# Canal实例配置(监控MySQL实例)

canal.instance.master.address=127.0.0.1:3306
canal.instance.dbUsername=canal
canal.instance.dbPassword=canal密码
canal.instance.connectionCharset=UTF-8

# 监控的库和表(支持正则)
canal.instance.filter.regex=shop_db.products,shop_db.orders

# Binlog位置(第一次留空自动从最新位置开始)
canal.instance.master.journal.name=
canal.instance.master.position=
<code"># 启动Canal
./bin/startup.sh

# 查看Canal日志
tail -f logs/canal/canal.log
tail -f logs/example/example.log

四、Python消费Canal并同步到ES和Redis

<code"># pip install canal-python elasticsearch redis --break-system-packages

import json
import time
from canal.client import Client
from canal.protocol import EntryProtocol_pb2
from elasticsearch import Elasticsearch
import redis

# 初始化连接
canal_client = Client()
canal_client.connect(host='127.0.0.1', port=11111)
canal_client.check_valid(username='', password='')
canal_client.subscribe(client_id='1001', destination='example', filter='.*\\..*')

es = Elasticsearch(['http://127.0.0.1:9200'])
r = redis.Redis(host='127.0.0.1', password='Redis密码', decode_responses=True)

def handle_product_change(event_type: str, before: dict, after: dict):
    """处理产品表变更"""
    product_id = after.get('id') or before.get('id')

    if event_type == 'DELETE':
        # 删除ES文档
        es.delete(index='products', id=product_id, ignore=[404])
        # 删除Redis缓存
        r.delete(f'product:{product_id}')
        print(f"产品 {product_id} 已删除,ES和Redis缓存已清理")
        return

    if event_type in ('INSERT', 'UPDATE'):
        # 更新ES文档(全文搜索)
        es.index(
            index='products',
            id=product_id,
            body={
                'id':          after['id'],
                'name':        after['name'],
                'description': after['description'],
                'price':       float(after['price']),
                'stock':       int(after['stock']),
                'category':    after['category'],
                'updated_at':  after['updated_at'],
            }
        )

        # 更新Redis缓存(直接更新而非删除,减少缓存穿透)
        cache_key = f'product:{product_id}'
        cached = r.hgetall(cache_key)
        if cached:  # 只有缓存存在时才更新(否则让自然填充)
            r.hset(cache_key, mapping={
                'name':  after['name'],
                'price': after['price'],
                'stock': after['stock'],
            })
            r.expire(cache_key, 3600)

        action = "新增" if event_type == 'INSERT' else "更新"
        print(f"产品 {product_id} {action},已同步到ES和Redis")

def parse_canal_entry(entry):
    """解析Canal Binlog条目"""
    if entry.entryType not in (
        EntryProtocol_pb2.EntryType.ROWDATA,
        EntryProtocol_pb2.EntryType.TRANSACTIONBEGIN,
        EntryProtocol_pb2.EntryType.TRANSACTIONEND,
    ):
        return

    if entry.entryType in (
        EntryProtocol_pb2.EntryType.TRANSACTIONBEGIN,
        EntryProtocol_pb2.EntryType.TRANSACTIONEND,
    ):
        return

    row_change = EntryProtocol_pb2.RowChange()
    row_change.MergeFromString(entry.storeValue)

    table_name = entry.header.tableName
    event_type = EntryProtocol_pb2.EventType.Name(row_change.eventType)

    for row in row_change.rowDatas:
        before = {col.name: col.value for col in row.beforeColumns}
        after  = {col.name: col.value for col in row.afterColumns}

        if table_name == 'products':
            handle_product_change(event_type, before, after)
        elif table_name == 'orders':
            handle_order_change(event_type, before, after)

# 主循环:持续消费Canal消息
print("开始监听MySQL Binlog变更...")
while True:
    try:
        message = canal_client.get(100)  # 一次获取最多100条
        entries = message.entries

        for entry in entries:
            parse_canal_entry(entry)

        if not entries:
            time.sleep(0.1)  # 无消息时短暂休眠

    except KeyboardInterrupt:
        break
    except Exception as e:
        print(f"处理Binlog错误:{e}")
        time.sleep(1)

canal_client.disconnect()

五、Systemd自动运行

<code"># /etc/systemd/system/canal-sync.service
[Unit]
Description=Canal Binlog Sync Service
After=network.target mysql.service

[Service]
Type=simple
User=canal
WorkingDirectory=/srv/canal-sync
ExecStart=/srv/canal-sync/venv/bin/python sync.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

六、监控同步延迟

<code"># 查看Canal消费延迟(Binlog位置)
curl -s http://127.0.0.1:11112/api/health

# 自定义监控:比较Canal消费位置和MySQL最新Binlog位置
#!/bin/bash
MYSQL_POS=$(mysql -u canal -p密码 -se "SHOW MASTER STATUS" | awk '{print $2}')
CANAL_POS=$(cat /srv/canal/logs/example/meta.log | tail -1 | grep -o 'position=[0-9]*' | cut -d= -f2)

LAG=$((MYSQL_POS - CANAL_POS))
echo "Binlog同步延迟:$LAG 字节"

if [ "$LAG" -gt 1048576 ]; then  # 超过1MB延迟告警
    echo "⚠️ Canal同步延迟过大!"
fi

七、总结

CDC + Canal是实现数据库与搜索引擎/缓存最终一致性的标准方案。相比双写,它将数据同步逻辑从业务代码中解耦,维护性更好,也避免了事务中多次写入的原子性问题。IDC.Net的香港VPS同账号内网互通,Canal服务器、MySQL主库、ES集群可以通过低延迟内网连接,同步延迟通常在毫秒级别。