Linux mysql主从配置

巧了我就是萌 提交于 2019-12-26 03:09:55

确保从数据库与主数据库里的数据一样

在主数据库里创建一个同步账号授权给从数据库使用

注意:需要在最开始就完成账号的创建与授权,不能在备份完数据库之后在给账户权限

mysql> create user 'repl'@'192.168.220.10' identified by 'repl123!';

mysql> grant replication slave on *.* to 'repl'@'192.168.220.10';

mysql> flush privileges;

配置主数据库

[root@localhost ~]# vim /etc/my.cnf
[root@localhost ~]# cat /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve

log-bin = mysql_bin
server-id = 10
[root@localhost ~]# service mysqld restart
Shutting down MySQL.. SUCCESS! 
Starting MySQL.. SUCCESS! 

查看库的状态

mysql> show master status\G
*************************** 1. row ***************************
             File: mysql_bin.000001
         Position: 154
     Binlog_Do_DB: 
 Binlog_Ignore_DB: 
Executed_Gtid_Set: 

配置从数据库

[root@localhost ~]# vim /etc/my.cnf
[root@localhost ~]# cat /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve

relay-log = mysql_relay
server-id = 20
[root@localhost ~]# service mysqld restart

mysql> change master to
    -> master_host='192.168.220.20',
    -> master_user='repl',
    -> master_password='repl123!',
    -> master_log_file='mysql_bin.000001',
    -> master_log_pos=154;

mysql> start slave;

两项必须为yes
mysql> show slave status \G
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes

主从同步

锁主库

mysql> flush tables with read lock;
mysql> insert student value(4,'sfdgs',23);
ERROR 1223 (HY000): Can't execute the query because you have a conflicting read lock

备份主库并将备份文件传送到从库

[root@localhost ~]# mysqldump -uroot -p123456 --all-databases > alldatabases.sql
[root@localhost ~]# scp alldatabases.sql root@192.168.220.30:/root/

在从库上恢复主库的备份并查看从库有哪些库,确保与主库一致

[root@localhost ~]# mysql -uroot -p123456 < alldatabases.sql

解除主锁

推出mysql即可解锁

查看状态

mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql_bin.000001 |     1578 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+

从库操作跟之前一样

查看数据库当前的进程

mysql> show processlist\G
*************************** 1. row ***************************
     Id: 8
   User: root
   Host: localhost
     db: NULL
Command: Query
   Time: 0
  State: starting
   Info: show processlist
1 row in set (0.01 sec)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!