MySQL 到 MongoDB 实时数据同步实操分享,带你轻松理解Python-Hook机制
from pymongo import MongoClient
from pymysql_replication import BinLogStreamReader
# 配置MySQL和MongoDB的连接信息
mysql_config = {
"host": "127.0.0.1",
"port": 3306,
"user": "your_mysql_user",
"password": "your_mysql_password"
}
mongo_config = {
"host": "127.0.0.1",
"port": 27017,
"db": "your_mongo_db",
"collection": "your_mongo_collection"
}
# 连接到MongoDB
client = MongoClient(mongo_config["host"], mongo_config["port"])
db = client[mongo_config["db"]]
collection = db[mongo_config["collection"]]
def sync_data(binlog_stream_reader):
for binlog in binlog_stream_reader:
for row in binlog.rows:
# 根据row的内容进行操作,这里只是示例
# 假设row['data']就是要插入的数据
collection.update_one({"id": row.data["id"]}, {"$set": row.data}, upsert=True)
# 连接到MySQL的binlog
stream_reader = BinLogStreamReader(
connection_settings=mysql_config,
server_id=123,
only_events=[INSERT, UPDATE, DELETE],
blocking=True,
log_file=None,
resume_stream=False,
only_tables=["your_db.your_table"]
)
# 启动同步数据的线程
sync_data(stream_reader)
这段代码展示了如何使用pymysql_replication
库来读取MySQL的binlog,并将变更实时同步到MongoDB中。这里使用了update_one
方法来更新MongoDB中的数据,并通过upsert=True
来确保如果记录不存在则插入新记录。这个例子简洁明了,并且教给了开发者如何使用Python来处理MySQL到NoSQL数据库的同步问题。
评论已关闭