在 MySQL 主从架构中,经常需要手动进行主从切换操作。以下是一个详细的脚本,用于将主节点切换为从节点,并确保无缝切换。这类场景可用于经常使用的一主一从架构,具体脚本如下:
mysqlChange.sh
#!/bin/bash
# 主节点和从节点的信息
master_host=$1 #"主节点IP"
slave_host=$2 #"从节点IP"
mysql_user="MySQL用户名"
mysql_password="MySQL密码"
mysql_port=3306
# 自定义虚拟 IP
virtual_ip=$3 #"192.168.1.100"
# 自定义虚拟 IP 的过程
echo "Creating virtual IP on the master..."
ssh $master_host "ifconfig eth0:0 $virtual_ip netmask 255.255.255.0 up"
# 获取原从节点的 file 和 position 信息
echo "Getting replication coordinates from the original slave..."
file_position=$(ssh $slave_host "mysql -u$mysql_user -p$mysql_password -e 'SHOW MASTER STATUS \G' | awk '/File/ {file=\$2} /Position/ {pos=\$2} END {print file\":\"pos}'")
# 手动切换主从角色
echo "Stopping replication on the slave..."
ssh $slave_host "mysql -u$mysql_user -p$mysql_password -e 'STOP SLAVE;'"
echo "Resetting master on the slave..."
ssh $slave_host "mysql -u$mysql_user -p$mysql_password -e 'RESET MASTER;'"
# 切换虚拟 IP
echo "Switching virtual IP addresses between master and slave..."
ssh $master_host "ifconfig eth0:0 down"
ssh $slave_host "ifconfig eth0:0 up $virtual_ip"
# 将主节点切换成从节点
echo "Stopping replication on the master and promoting the slave..."
ssh $master_host "mysql -u$mysql_user -p$mysql_password -e 'RESET SLAVE; RESET MASTER; CHANGE MASTER TO MASTER_HOST=\"$master_host\", MASTER_PORT=$mysql_port, MASTER_USER=\"$mysql_user\", MASTER_PASSWORD=\"$mysql_password\", MASTER_LOG_FILE=\"$(echo $file_position | cut -d':' -f1)\", MASTER_LOG_POS=$(echo $file_position | cut -d':' -f2); START SLAVE;'"
echo "Main and slave roles have been switched successfully!"
调用脚本
#!/bin/bash
# 主节点和从节点的信息
master_host="192.168.10.10"
slave_host="192.168.10.11"
# 自定义虚拟 IP
virtual_ip="192.168.1.100"
# 调用脚本
bash mysqlChange.sh $master_host $slave_host $virtual_ip
这个脚本实现了将主节点切换为从节点的流程,并在过程中确保了虚拟 IP 的切换和主从关系的正确建立。
标签:slave,完美,host,一主一,master,切换,mysql,MASTER,节点 From: https://blog.51cto.com/u_14316134/8957067