MySQL主从切换(Master-Slave Switchover)是指在MySQL复制环境中,将原本的从库(Slave)提升为新的主库(Master),而原来的主库降级为从库的过程。这种操作通常用于实现高可用性和故障恢复。
以下是一个简单的MySQL主从切换脚本示例,使用Python和mysql-connector-python
库:
import mysql.connector
from mysql.connector import Error
def switch_master_slave(master_host, slave_host, user, password):
try:
# 连接到当前主库
master_conn = mysql.connector.connect(host=master_host, user=user, password=password)
master_cursor = master_conn.cursor()
# 停止从库的复制
slave_conn = mysql.connector.connect(host=slave_host, user=user, password=password)
slave_cursor = slave_conn.cursor()
slave_cursor.execute("STOP SLAVE;")
slave_cursor.execute("RESET SLAVE ALL;")
# 更新从库的主库信息
slave_cursor.execute(f"CHANGE MASTER TO MASTER_HOST='{master_host}', MASTER_USER='{user}', MASTER_PASSWORD='{password}', MASTER_AUTO_POSITION=1;")
slave_cursor.execute("START SLAVE;")
# 更新主库的复制信息
master_cursor.execute("STOP SLAVE;")
master_cursor.execute("RESET SLAVE ALL;")
master_cursor.execute(f"CHANGE MASTER TO MASTER_HOST='{slave_host}', MASTER_USER='{user}', MASTER_PASSWORD='{password}', MASTER_AUTO_POSITION=1;")
master_cursor.execute("START SLAVE;")
print("Master-Slave switch successful!")
except Error as e:
print(f"Error: {e}")
finally:
if master_conn.is_connected():
master_cursor.close()
master_conn.close()
if slave_conn.is_connected():
slave_cursor.close()
slave_conn.close()
# 示例调用
switch_master_slave('old_master_host', 'new_master_host', 'username', 'password')
通过以上步骤和脚本示例,可以实现基本的MySQL主从切换操作。在实际应用中,可能需要根据具体需求进行调整和优化。
领取专属 10元无门槛券
手把手带您无忧上云