话不多说直接上代码,简单实现,具体功能请根据业务场景自行调整
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import DeleteRowsEvent, UpdateRowsEvent, WriteRowsEvent
import sys
import threading
import traceback
import time
import pymysql
mysql_settings = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'passwd': '123'
}
# 监听数据库
db_schemas = ['database_1']
# 同步数据库
sync_schemas = 'database_2'
# 监听数据表
listen_tables = ['table1', 'table2', 'table3']
# 待处理数据队列
wait_handle_queue = []
def main():
# 实例化binlog 流对象
stream = BinLogStreamReader(
connection_settings=mysql_settings,
server_id=1, # slave标识,唯一
blocking=True, # 阻塞等待后续事件
# 设定只监控写操作:增、删、改
only_schemas=db_schemas,
only_tables=listen_tables,
freeze_schema=True,
only_events=[
DeleteRowsEvent,
UpdateRowsEvent,
WriteRowsEvent
]
)
print('数据库增删改事件监听启动...')
for binlogevent in stream:
try:
# binlogevent.dump() # 打印所有信息
for row in binlogevent.rows:
# 打印 库名 和 表名
event = {
"schema": binlogevent.schema,
"table": binlogevent.table,