(十六)简单配置mysql数据库主从同步、读写分离

本文为学习笔记,主要用于记录本人学习过程。部分内容为转载!!!!

一、进行Mysql的主从同步复制、读写分离的原因?

对于当下的一些大型网站,仅仅一个数据库服务器已经不足以处理大量的数据库连接操作。而且仅仅拥有一个数据库服务器,容易造成数据丢失,非常不安全。

部署主从服务器,实现主从数据的同步,并实现读写分离,减轻主服务器的压力,也缓解了数据丢失的问题。

主从服务器,实际是指一主多从,在主服务器上进行写操作,而所有的读操作都在从服务器上进行。

主从服务器实现模型:

在这里插入图片描述

从以上模型可以看出,从服务器的日志文件相对于主服务器的日志文件而言,存在着延迟。

二、主从同步复制的方式

1、同步复制

即每一个在主服务器上的数据库操作,都需要等待从服务器复制完成,主服务器才会进行下一个数据库操作。

2、异步复制

即主服务器上一直不停的做数据库操作,而从服务器就一直复制日志实现同步。

三、主从复制原理

(1)主数据库进行增删改操作后,相应操作记录的语句(比如 create database test)会记录到binlog日志文件中(binlog日志文件一般和数据库data文件夹在一起)。

(2)从数据库会请求主数据库的binlog日志文件,获取到新的操作语句,然后在自己的从数据库上自动执行相同的操作语句,进而实现主从的同步。

注:这里,我们所需要配置的只是主从环境以及开启binlog日志,其他的mysql会自动完成。

四、详细主从复制过程

(1)Master开启bin-log功能,binlog日志文件用于记录数据库的增删改操作。

(2)需要开启三个线程,Master:I/O线程;Slave:I/O线程,SQL线程。

(3)Slave start;通过I/O线程连接Master,并且请求某个bin-log,position之后的内容。

(4)Master服务器收到Slave I/O线程发过来的日志请求信息,然后Master I/O线程将bin-log内容、position返回给Slave IO线程。

(5)Slave服务器收到bin-log日志内容,将bin-log日志内容写入到relay-log中继日志,创建一个master.info文件,该文件记录master IP、用户名、密码、master bin-log名称、bin-log position。

(6)Slave已经开启了sql线程,由sql线程实时监测relay-log日志内容是否有更新,如果有更新,则解析文件中的sql语句,并在Slave数据库中执行相同的操作语句。

注:可以通过show slave status \G  来查看具体的中继日志路径以及连接的master的其他信息。 

五、主从数据库实现

0、环境配置:

主服务器IP地址:192.168.112.130
从服务器IP地址:192.168.112.131

1、安装配置mysql数据库(自行搜索安装)

# 创建一个测试数据库
[root@master ~]# mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.23 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> create database test;
Query OK, 1 row affected (0.00 sec)

mysql> exit
Bye

用同样的方法在slave上安装mysql,创建test数据库。

# mysql在不知道root密码的情况下重设root密码,编辑/etc/my.cnf文件,添加以下内容。
[mysqld]
skip-grant-tables
# 重启mysql数据库
# 此时可以无密码进行登录
[root@master ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.23 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> set password for root@localhost = password('123456');
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> exit
Bye

# 最后再编辑/etc/my.cnf文件,注释掉skip-grant-tables
# 重启mysql数据库即可用刚设置的新密码进行登录了。

2、修改master主服务器配置

# 修改/etc/my.cnf如下:
[mysql]
default-character-set=utf8

[mysqld]
default-storage-engine=INNODB
character_set_server=utf8

server-id = 1
log_bin = master-bin
binlog_format = ROW
binlog_do_db = test

#server-id 服务器唯一标识。
#log_bin 主服务器的mysql二进制日志,提供给从服务器用于同步数据。只用需要同步的数据库的操作才会记录在日志里。
#binlog_format  二进制日志文件格式
#以下二选一:
#binlog_do_db 指定同步的数据库名
#binlog_ignore_db 指定不同步的数据库名
# 授予主服务器上root用户连接从服务器的权限
[root@localhost mysql]# mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.17-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> grant replication slave on *.* to root@192.168.112.131 identified by '123456';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye
# 查看主服务器的状态
[root@master ~]# systemctl restart mysql
[root@master ~]# mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.23-log MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000001 |      154 | test         |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

3、修改slave从服务器配置

# 修改/etc/my.cnf如下:
[mysql]
default-character-set=utf8

[mysqld]
default-storage-engine=INNODB
character_set_server=utf8

server-id = 2
log-bin=master-bin
binlog_format = ROW


#relay-log=slave-relay-bin
#relay-log-index = slave-relay-bin.index
#replicate-do-db=test
#server-id 服务器唯一标识。
#relay-log 从服务器的mysql二进制日志,用于数据恢复和备份。当主服务器崩了,提供给其他从服务器作为主服务器是用。
#以下二选一:
#replicate-do-db 指定同步的数据库名
#replicate-ignore-db 指定不同步的数据库名
[root@slave-server ~]# systemctl restart mysql
[root@localhost ~]# mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.17-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> stop
    -> slave;
Query OK, 0 rows affected (0.00 sec)

mysql> stop slave;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> stop slave;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> CHANGE MASTER TO MASTER_HOST='192.168.112.130',MASTER_PORT=3306,MASTER_USER='root',MASTER_PASSWORD='123456',MASTER_LOG_FILE='master-bin.000005',MASTER_LOG_POS= 154;
Query OK, 0 rows affected, 2 warnings (0.00 sec)
#master_host  【主服务器的IP地址】
#master_port  【主服务器的端口】
#master_log_file   【show master status显示的File列:master-bin.000001】
#master_log_pos    【show master status显示的Position列:154】

mysql> start slave;
Query OK, 0 rows affected (0.00 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: 
                  Master_Host: 192.168.112.130
                  Master_User: root
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000005
          Read_Master_Log_Pos: 154
               Relay_Log_File: localhost-relay-bin.000001
                Relay_Log_Pos: 4
        Relay_Master_Log_File: master-bin.000005
             Slave_IO_Running: No
            Slave_SQL_Running: Yes
              Replicate_Do_DB: test
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 154
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 1593
                Last_IO_Error: Fatal error: The slave I/O thread stops because master and slave have equal MySQL server UUIDs; these UUIDs must be different for replication to work.
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 200514 10:47:34
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

ERROR: 
No query specified

# 显示结果为server_uuid 冲突  修改auto.cnf文件数据重启即可
mysql> show variables like '%server_uuid%';
+---------------+--------------------------------------+
| Variable_name | Value                                |
+---------------+--------------------------------------+
| server_uuid   | 24fbce5b-266b-11e7-b0a7-5254008815b6 |
+---------------+--------------------------------------+
1 row in set (0.00 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: 
                  Master_Host: 192.168.112.130
                  Master_User: root
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000005
          Read_Master_Log_Pos: 154
               Relay_Log_File: localhost-relay-bin.000001
                Relay_Log_Pos: 4
        Relay_Master_Log_File: master-bin.000005
             Slave_IO_Running: No
            Slave_SQL_Running: Yes
              Replicate_Do_DB: test
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 154
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 1593
                Last_IO_Error: Fatal error: The slave I/O thread stops because master and slave have equal MySQL server UUIDs; these UUIDs must be different for replication to work.
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 200514 10:47:34
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

ERROR: 
No query specified

mysql> stop slave;
Query OK, 0 rows affected (0.00 sec)

mysql> start slave;
Query OK, 0 rows affected (0.00 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.112.130
                  Master_User: root
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000006
          Read_Master_Log_Pos: 154
               Relay_Log_File: localhost-relay-bin.000003
                Relay_Log_Pos: 369
        Relay_Master_Log_File: master-bin.000006
             Slave_IO_Running: Yes  # 同时为yes是配置成功
            Slave_SQL_Running: Yes  # 同时为yes是配置成功
              Replicate_Do_DB: test
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 747
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 24fbce5b-266b-11e7-b0a7-5254008815b7
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

ERROR: 
No query specified

mysql> exit
Bye
# 针对Slave_IO_Running处于连接中状态的解决方法:
             Slave_IO_Running: Connecting
            Slave_SQL_Running: Yes
# 授予root所有权限all privileges
grant all privileges on *.* to root@192.168.112.130 identified by '123456' with grant option; 
# 刷新权限
flush privileges;


# 注意查看异常信息即可

4、测试主从服务器工作情况

主服务器IP地址:192.168.112.130
从服务器IP地址:192.168.112.131
测试:在主服务器上创建表,并插入数据。看从服务器是否会进行同步。
①主服务器上建数据

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` varchar(10) NOT NULL,
  `name` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES ('1', 'abong');
INSERT INTO `user` VALUES ('2', 'zhang');

②检验从服务器是否同步。从下图可以看到,在从服务器上已经有了user表,并且数据也是正确的。

③从库上修改数据

④主库上看数据是否被修改。可以看到,数据并没有被修改。

六、读写分离

在MYSQL数据库主从同步、读写分离这项技术中,最主要的是如何做到主从同步,而读写分离可以通过数据库用户的权限进行配置。从上面的测试结果可以看出,将主库作为写库,而从库作为读库,可以将数据库的读写操作分离开,减轻数据库的压力,还能保持数据库的一致性。
在主库上,创建一个mysql用户,赋予读写权限。
在从库上,创建一个mysql用户,赋予只读权限。

 

 

 

 

 


————————————————
原文链接:https://blog.csdn.net/weixin_36522099/article/details/106123612

原文链接:https://blog.csdn.net/m_nanle_xiaobudiu/article/details/81086243

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值