目录
一、拉取镜像
二、运行镜像
三、可能会出现的问题:镜像容器自动停止。
四、进入canal容器(目的是拷贝配置文件到宿主主机)
五、拷贝canal配置文件
六、开启数据库 Binlog 写入功能并建立一个canal账号
七、修改配置文件(instance.properties)
八、关闭之前的容器,重启新容器
九、python客户端
十、保证canal服务、mysql服务、客户端服务三方网络畅通
十一、测试
docker pull canal/canal-server
docker run --name canal -d canal/canal-server
docker logs canal
原因:主机内存太小。
解决:内存搞大点。
docker exec -it canal bash
在主机下新建文件夹/home/canal/conf
docker cp canal:/home/admin/canal-server/conf/canal.properties /home/canal/conf
docker cp canal:/home/admin/canal-server/conf/example/instance.properties /home/canal/conf
[mysqld]
log-bin=mysql-bin # 开启 binlog
binlog-format=ROW # 选择 ROW 模式
server_id=1 # 配置 MySQL replaction 需要定义,不要和 canal 的 slaveId 重复
CREATE USER canal IDENTIFIED BY 'canal';
GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'canal'@'%';
-- GRANT ALL PRIVILEGES ON *.* TO 'canal'@'%' ;
FLUSH PRIVILEGES;
docker stop canal
docker rm canal
#启动新的 这里-v是将外部的文件挂载到容器内部 这样就不用每次启动都要配置参数了
docker run --name canal -p 11111:11111 -d \
-v /home/canal/conf/instance.properties:/home/admin/canal-server/conf/example/instance.properties \
-v /home/canal/conf/canal.properties:/home/admin/canal-server/conf/canal.properties \
-v /home/canal/log/:/home/admin/canal-server/logs/ \
canal/canal-server
pip install canal-python
import time
from canal.client import Client
from canal.protocol import EntryProtocol_pb2
from canal.protocol import CanalProtocol_pb2
client: Client = Client()
client.connect(host='192.168.1.71', port=11111)
# client.connect(host='127.0.0.1', port=11111)
client.check_valid(username=b'', password=b'')
client.subscribe(client_id=b'1001', destination=b'example', filter=b'.*\\..*')
if __name__ == '__main__':
while True:
message = client.get(100)
entries = message['entries']
for entry in entries:
entry_type = entry.entryType
if entry_type in [EntryProtocol_pb2.EntryType.TRANSACTIONBEGIN, EntryProtocol_pb2.EntryType.TRANSACTIONEND]:
continue
row_change = EntryProtocol_pb2.RowChange()
row_change.MergeFromString(entry.storeValue)
event_type = row_change.eventType
header = entry.header
database = header.schemaName
table = header.tableName
event_type = header.eventType
for row in row_change.rowDatas:
format_data = dict()
if event_type == EntryProtocol_pb2.EventType.DELETE:
format_data['event_type_name'] = '删除'
for column in row.beforeColumns:
format_data[column.name] = column.value
elif event_type == EntryProtocol_pb2.EventType.INSERT:
format_data['event_type_name'] = '新增'
for column in row.afterColumns:
format_data[column.name] = column.value
else:
format_data['event_type_name'] = '更新'
format_data['before'] = format_data['after'] = dict()
for column in row.beforeColumns:
format_data['before'][column.name] = column.value
for column in row.afterColumns:
format_data['after'][column.name] = column.value
data = dict(
db=database,
table=table,
event_type=event_type,
data=format_data,
)
print(data)
time.sleep(1)
client.disconnect()
①canal与mysql畅通(在canal主机上ping mysql主机)
②canal与客户端畅通(在mysql主机上ping客户端主机)
数据库新增一条数据、修改一条数据