首先准备四台虚拟机。关闭防火墙和selinux,并下载mariadb,四个虚拟机都进行以下操作:
#关闭防火墙
systemctl stop firewalld
systemctl disable firewalld
#文件编辑关闭selinux:
sed -i '/^SELINUX=.*/c SELINUX=disabled' /etc/selinux/config
setenforce 0
yum -y install mariadb*
#开启Mysql服务,并查看服务状态
systemctl start mariadb
systemctl status mariadb
#设置密码
mysql_secure_installation
#将密码设置为123,方便下面操作
主库1开启binlog,配置唯一server ID,创建一个单独用户用于从库请求binlog,并设置编码格,提高数据库的兼容性和可维护性,确保数据库系统在处理不同语言和字符时的稳定性和可靠性
vi /etc/my.cnf
#找到[mysqld]并插入以下内容:
log-bin=mysql-bin
server-id=1
binlog-ignore-db=mysql
binlog-ignore-db=information_schema
binlog-ignore-db=performance_schema
binlog-ignore-db=sys
#编码格
init-connect='SET NAMES UTF8'
skip-character-set-client-handshake
character-set-server=utf8
主库2开启binlog,配置唯一server ID,创建一个单独用户用于从库请求binlog,并设置编码格
vi /etc/my.cnf
#找到[mysqld]并插入以下内容:
log-bin=mysql-bin
server-id=2
binlog-ignore-db=mysql
binlog-ignore-db=information_schema
binlog-ignore-db=performance_schema
binlog-ignore-db=sys
#编码格
init-connect='SET NAMES UTF8'
skip-character-set-client-handshake
character-set-server=utf8
主库1和主库2都添加级联动作,使本虚拟机的从可以同步本虚拟机的主
vi /etc/my.cnf
#找到[mysqld]并插入以下内容:
log_slave_updates=1
从库1配置一个唯一的server ID,配置relay log,并设置编码格
vi /etc/my.cnf
#找到[mysqld]并插入以下内容:
server-id=3
relay-log=mysql-relay-bin
replicate-ignore-db=mysql
replicate-ignore-db=information_schema
replicate-ignore-db=performance_schema
replicate-ignore-db=sys
#编码格
init-connect='SET NAMES UTF8'
skip-character-set-client-handshake
character-set-server=utf8
从库2配置一个唯一的server ID,配置relay log
vi /etc/my.cnf
#找到[mysqld]并插入以下内容:
server-id=4
relay-log=mysql-relay-bin
replicate-ignore-db=mysql
replicate-ignore-db=information_schema
replicate-ignore-db=performance_schema
replicate-ignore-db=sys
#编码格
init-connect='SET NAMES UTF8'
skip-character-set-client-handshake
character-set-server=utf8
四台虚拟机,重启mariadb,并登录数据库
systemctl restart mariadb
mysql -uroot -p123
两个主库授权远程用户
CREATE USER 'shz'@'%' IDENTIFIED BY '123';
grant REPLICATION SLAVE on *.* to 'shz'@'%' identified by '123';
grant all privileges on *.* to 'root'@'%' identified by '123';
flush privileges;
配置从库连接到主库,MASTER_LOG_FILE与MASTER_LOG_POS的值由主库信息获得;
(主库:show master status;)
从1配主1,从2配主2,两主互配
CHANGE MASTER TO
MASTER_HOST='主库IP',
MASTER_USER='shz',
MASTER_PASSWORD='123',
MASTER_PORT=3306,
MASTER_LOG_FILE='mysql-bin.000004', #数值对照上图替换
MASTER_LOG_POS=670; #数值对照上图替换
敲一下命令查看是否配置成功,红色部分为yes,即为配置成功,可在主库创建或删除数据库,从库看是否同步
start slave;
show slave status \G;