理解Mysql主从服务器
主从服务器解决了4个问题:
数据分布
负载平衡(load balancing)
备份
高可用性(high availability)和容错
工作原理
从高层来看,主从服务器复制分成三步:
master将改变记录到二进制日志(binary log)中,这些记录叫做二进制日志事件,binary log events
slave将master的binary log events 拷贝到它的中继日志relay log中
slave的sql thread读取relay log的数据并将数据写入到自己的数据库中
Mysql主从配置
配置主服务器:
安装Mysql:
sudo apt-get install mysql-server
配置Mysql:
主Mysql服务器192.168.0.100
从Mysql服务器192.168.1.101
配置主服务器:
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
#bind-address = 127.0.0.1
server-id = 1
log_bin = /var/log/mysql/mysql-master-bin.log
expire_logs_days = 10
max_binlog_size = 100M
#binlog_do_db = include_database_name
binlog_ignore_db = mysql
配置从服务器账户和权限:
mysql> grant replication slave on . to 'backup'@'192.168.0.101' identified by '123455';
mysql> flush privileges;
sudo service mysql restart
查看主服务器状态:
mysql> show master status;
• 记录 File 值 Position值
配置从服务器:
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
server-id = 2
relay_log = /var/log/mysql/mysql-slave-relay.log
read_only = 1
log_slave_updates = 1
sudo service mysql restart
mysql> change master to
master_host='192.168.1.100',
master_port=3306,
master_user='master',
master_password='123456',
master_log_file='mysql-master1-bin.000001',
master_log_pos=154;
• master_log_file 上面记录的 File 值
• master_log_pos 上面记录的 Position值
• master_log_file和master_log_pos可以通过在主服务器使用 show master status; 获得
启动从服务器
mysql> start slave;
mysql> show slave status G;
启动后主要确认Slave_IO_Running和Slave_SQL_Running是Yes状态。
注:如果出现密码长度错误
set global validate_password_policy=0; #密码强度设为最低等级
set global validate_password_length=4; #密码允许最小长度为4
flush privileges; #更新授权表,生效