(13) MySQL master-slave replication

(1) Working principle

(2) Master-slave implementation

1) Environment introduction

/etc/redhat-release 
CentOS Linux release 7.3.1611 (Core)

MySQL version: 5.7

mysql> select version();
+------------+
| version()  |
+------------+
| 5.7.22-log |
+------------+

2) master side configuration

  • Prepare data

    mysql>  mysql -uroot -pRedhat@123 -e 'create database testdb;
    mysql>  create table testdb.t1(id int,name varchar(50));
    mysql>  insert into testdb.t1 values(1,'jack');
    mysql>  insert into testdb.t1 values(2,'alex');
  • Enable binary logging and configure server-id

    #vim /etc/my.cnf
    log-bin
    server-id=1
  • restart the server

    #systemctl restart mysqld
  • Create an authorized account

    mysql> grant replication slave,replication client on *.* to 'rep'@'192.168.111.%' identified by 'Reprep@123';
    mysql> flush privileges;
  • backup database

    mysqldump -uroot -pRedhat@123 -A -R  --single-transaction --master-data=1 --flush-logs >$(date +%F)-mysql-all.sql
  • Copy the backup database file to the slave host

    scp -r 2018-04-26-mysql-all.sql [email protected]:/root
  • After creating some data after full backup

    mysql> insert into testdb.t1 values(3,'www');
    mysql> insert into testdb.t1 values(4,'yyyy');

    3) Slave side configuration

  • Verify whether the account created by the main library can log in normally, and also verify whether there is a firewall problem

    # mysql -h192.168.111.151 -urep -p'Reprep@123'
  • Configure the server-id of the slave library and set the slave library to be read-only.
    Pay attention to the permission of the application to connect to the slave library. Do not give all permissions, only make the slave library read-only.

    #vim /etc/my.cnf
    server-id=2
    read-only 
  • restart the database

    #systemctl restart mysqld
  • Import the backup to the slave library: It is strongly recommended to use the source method to import sql backup to the slave library. It is
    not recommended to use mysql -uroot -pRedhat@123 </root/2018-04-26-mysql-all.sql, otherwise the change master needs to Specify pos file and location point

    mysql>source /root/2018-04-26-mysql-all.sql   
  • Link to the main library

    mysql> change master to 
    -> master_host='192.168.111.151',               \\生成环境建议使用主机名,不建议使用ip地址
    -> master_user='rep',
    -> master_password='Reprep@123';
  • Enable replication and verification status

    mysql> start slave;
    mysql> show slave status\G
      Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
  • verify the data

    mysql> select * from testdb.t1;
    +------+------+
    | id   | name |
    +------+------+
    |    1 | jack |
    |    2 | alex |
    |    3 | www  |
    |    4 | yyyy |
    +------+------+

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324985902&siteId=291194637