您当前的位置:首页 > 计算机 > 软件应用 > 数据库 > MySQL

mysql的主从复制(含位点复制和GTID复制)的代码实例

时间:07-22来源:作者:点击数:
城东书院 www.cdsy.xyz

提示:

master主库ip地址:192.168.137.2

从库s1的ip地址:192.168.137.11

从库s2的ip地址:192.168.137.22

主从复制的原理:

MySQL主从复制是一个异步的复制过程,主要是通过二进制日志(binary log)文件实现。下面是主从复制的基本原理:

  1. 主服务器记录二进制日志:在主服务器上,每个更改数据的事件都会被记录到二进制日志中。
  2. 从服务器请求二进制日志:从服务器连接到主服务器,请求从指定日志位置之后的事件。
  3. 主服务器发送二进制日志:主服务器通过网络发送这些事件给从服务器。
  4. 从服务器记录二进制日志:从服务器将接收到的事件记录到自己的中继日志(relay log)中。
  5. 从服务器应用中继日志:从服务器读取中继日志中的事件并应用到自己的数据库中。

一、从零部署GTID复制

从0部署GTID复制(一)

1.开启GTID模式

GTID在my.cnf文件中最重要的配置:

log-bin=日志文件路径 #主从复制的前提

gtid_mode=ON #开启GTID模式

enforce_gtid_consistency=ON

2.查看master主库binlog是否开启
mysql> show global variables like "log_bin";

如果没有开启,就算再mysql命令行中修改为启动了,也要在my.cnf中设置log-bin,防止重启后,binlog未开启的情况

3.查看server_id
mysql> select @@global.server_id;

注意:主从的server_id不要设置成一样

没有或者与预期不符的,在my.cnf中修改server-id

4.从库做同样的操作

master主库my.cnf完整文件内容:

[client]
port        = 3306
socket      = /tmp/mysql.sock

[mysqld]
port    = 3306
socket  = /tmp/mysql.sock


##  dir set
datadir           = /usr/local/mysql/data
innodb_data_home_dir   = /usr/local/mysql/data
innodb_log_group_home_dir = /usr/local/mysql/data
log-bin           = /usr/local/mysql/binlog/mysql-bin
log_bin_index             = /usr/local/mysql/binlog/mysql-bin.index  
relay-log         = /usr/local/mysql/binlog/mysql-relay-bin
tmpdir            = /usr/local/mysql/tmpdir
slow_query_log_file   = /usr/local/mysql/log/mysql-slow.log
general_log_file   = /usr/local/mysql/log/mysql-general.log
log-error         = /usr/local/mysql/log/mysql.err

## slave and binlog
server-id = 6666            #   
skip-slave-start = 0        #
read_only = 0           #
binlog_format = row             
log-slave-updates = 1
master_info_repository = table
relay_log_info_repository = table
relay_log_purge = 1
relay_log_recovery = 1
sync_binlog = 100

binlog_cache_size = 1M
expire_logs_days = 30
log_bin_trust_function_creators = 1         
slave_net_timeout=60                
#binlog_error_action="IGNORE_ERROR"     

innodb_autoinc_lock_mode=1          

## 
back_log = 200
bulk_insert_buffer_size = 8M            
#character-set-server = utf8
lower_case_table_names = 1              #  1:不区分大小写

## 基线
local-infile = off
skip-networking = off
skip-name-resolve = on 

## connect
max_allowed_packet = 32M
max_connect_errors = 1000
max_connections = 3000
wait_timeout = 3600             # 连接之前等待活动的秒数 default:8h
interactive_timeout = 3600          # 连接之前等待活动的秒数 default:8h

table_open_cache = 4096
thread_cache_size =  64
thread_stack = 192K
transaction-isolation = REPEATABLE-READ
pid-file = mysql1.pid

## slow
slow_query_log = 1              
long_query_time = 1
log-slow-admin-statements
log_queries_not_using_indexes = 0
slow_launch_time = 1
read_buffer_size = 4M               
read_rnd_buffer_size = 8M           
sort_buffer_size = 8M
join_buffer_size = 32M
tmp_table_size = 128M
max_heap_table_size = 128M

default-storage-engine = innodb
explicit_defaults_for_timestamp = on           

## innodb
innodb_buffer_pool_size = 1G                    
innodb_max_dirty_pages_pct = 80         
innodb_thread_concurrency = 8           
innodb_buffer_pool_instances = 1        
innodb_flush_log_at_trx_commit = 2      
innodb_read_io_threads = 8          
innodb_write_io_threads = 4         
innodb_io_capacity = 1000
innodb_io_capacity_max = 2000
innodb_lru_scan_depth = 1024
innodb_use_native_aio = 1
innodb_flush_neighbors = 1
innodb_buffer_pool_load_at_startup = 1
innodb_buffer_pool_dump_at_shutdown = 1

innodb_data_file_path=ibdata:1G:autoextend
innodb_log_files_in_group = 3
innodb_log_file_size = 2G
innodb_file_per_table = 1 

innodb_flush_method = O_DIRECT
innodb_strict_mode = 1
innodb_lock_wait_timeout = 30
innodb_log_buffer_size = 16M
innodb_adaptive_flushing = 1
innodb_change_buffering = all
innodb_purge_threads = 4            
innodb_purge_batch_size = 300           

innodb_old_blocks_time = 1
innodb_fast_shutdown = 0
performance_schema = 1
innodb_print_all_deadlocks = 1
innodb_sort_buffer_size = 4M 

innodb_page_size = 16k
gtid_mode=on
enforce_gtid_consistency=on     

table_open_cache_instances=16
binlog_rows_query_log_events=1      

slave_parallel_workers = 0          # 多线程复制线程数
#slave_parallel_type=LOGICAL_CLOCK      
#binlog_group_commit_sync_delay = 500000  
#binlog_group_commit_sync_no_delay_count =12  

## pasword
default_password_lifetime=0                     # 0密码永不过期,N n天过期

[mysqldump]
quick
max_allowed_packet = 32M

[mysql]
no-auto-rehash
prompt=p@d>_

[mysqld_safe]
open-files-limit = 28192

[mysqlhotcopy]
interactive-timeout

从库的就在master主库的my.cnf文件的基础上修改server-id的值就行了

5.重启mysql

从0部署GTID复制(二)

1.主库创建用户
CREATE USER 'repl'@'%' identified WITH mysql_native_password BY 'Alice123!';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';
2.主库导出数据

可以考虑使用mysqldump,xtrabackup,clone plugin

mkdir -p /data/backup/
cd /data/backup/
mysqldump -uroot -p --single-transaction --all-databases --master-data=2 --set-gtid-purged=on >alldb_bak_for_gtid.sql
3.把备份文件从master主库拷贝到s1从库

从库的system控制台:

mkdir -p /data/backup

主库的system控制台:

scp alldb_bak_for_gtid.sql root@192.168.137.11:/data/backup
4.从库导入数据
(1)重置二进制日志索引文件

MySQL的RESET MASTER命令的主要作用是删除所有现有的二进制日志文件并重置二进制日志索引文件,‌将服务器重置为启动二进制日志记录之前的状态

mysql> reset master;
(2)再导入数据
cd /data/backup
mysql -uroot -p < alldb_bak_for_gtid.sql

从0部署GTID复制(三)

1.在从库中关闭slave,重置slave,配置change mater to...,start slave四件套
stop slave;
reset slave;

change master to 
master_host='192.168.137.2',
master_user='repl',
master_password='Alice123!',
MASTER_AUTO_POSITION=1;

start slave;
2.从库中查看复制状态
mysql> show slave status\G

*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.137.2
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000003
          Read_Master_Log_Pos: 1870
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 418
        Relay_Master_Log_File: mysql-bin.000003
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          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: 1870
              Relay_Log_Space: 627
              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: 2666
                  Master_UUID: 0b796d2d-431b-11ef-a867-000c29012dba
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more u                                                                                                  pdates
           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: 0b796d2d-431b-11ef-a867-000c29012dba:1-8
                Auto_Position: 1
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
       Master_public_key_path:
        Get_master_public_key: 0
            Network_Namespace:
1 row in set, 1 warning (0.00 sec)

3.测试数据是否同步

主库执行:

create table xxx; // 建表语句,略。。。
insert into xxx; // 插入数据语句,略。。。

从库查询:

mysql> use db1
mysql> show tables;
mysql> select * from 主库新建的表;
mysql> show slave status\G
。。。略。。。
   Slave_IO_Running: Yes
   Slave_SQL_Running: Yes
。。。略。。。

注意:Slave_IO_Running和Slave_SQL_Running必须都是yes

二、一主两从和级联架构之间要怎么切换?

【一】创建一主两从架构(基于位点复制)

1.在主库创建复制用户
mysql> CREATE USER 'repl'@'%' identified WITH mysql_native_password BY 'Alice123!';
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';

2.主库导出数据
cd /data/backup
xtrabackup --defaults-file=/etc/my.cnf -uroot -p --backup --stream=xbstream --target-dir=./ >/data/backup/xtrabackup.xbstream
3.主库完全备份文件拷贝到从库
(1)从库创建恢复目录
mkdir /data/backup/recover
(2)主库把备份sql文件拷贝到两个从库
scp xtrabackup.xbstream root@192.168.137.22:/data/backup/recover
(3)停掉从库mysql实例
service mysql stop
(4)清空新实例数据目录和binlog目录
rm /usr/local/mysql/data/* -rf
rm /usr/local/mysql/binlog/* -rf
(5)把全备恢复到新的mysql中
cd /data/backup/recover
xbstream -x < xtrabackup.xbstream
xtrabackup --prepare --target-dir=./

xtrabackup --defaults-file=/etc/my.cnf --copy-back --target-dir=./
(6)启动mysql
service mysql start
(7)查看备份时的位点信息
cat xtrabackup_binlog_info
(8)在两台从库创建复制关系(位点复制方式)

注意:如果想要改成GTID复制,change master to语句中,去掉bin_log_file和bin_log_pos参数,添加MASTER_AUTO_POSITION=1

show slave status\G

CHANGE MASTER TO
MASTER_HOST='192.168.137.2',
MASTER_USER='repl',
MASTER_PASSWORD='Alice123!',
master_log_file='xxx', // 去master_host对应ip地址的mysql实例中使用"show master status;"获取
master_log_pos=xxx; // 去master_host对应ip地址的mysql实例中使用"show master status;"获取

start slave;

在从库中查看主从状态

show slave status\G
4.测试同步

(1)主库写入

use db1

create table repl_test(id int);
insert into repl_test select 1;

(2)从库查询

use db1
select * from repl_test;

【二】一主两从改成级联(基于位点)

1.断开s2的复制
mysql> stop slave;
2.断开s1的复制
mysql> stop slave;
3.s1查看当前位点
mysql> show master status;
4.s1启动复制
mysql> start slave;
mysql> show slave status;
略...
Relay_Master_Log_File: 从库执行到的主库的日志文件
Exec_Master_Log_Pos: 从库执行到的主库的位点
略...
5.s2启动复制,同步到s1相同的位置

注意:

(1)MASTER_LOG_FILE=s1实例中使用"show slave status;"命令后显示的内容中Relay_Master_Log_File对应的值

(2)MASTER_LOG_POS=s1实例中使用"show slave status;"命令后显示的内容中Exec_Master_Log_Pos对应的数值

mysql> start slave UNTIL MASTER_LOG_FILE ="xxx",  MASTER_LOG_POS=xxx;

查看复制状态

show slave status\G
6.s2连接到s1:

眼熟的停止slave,重置slave,change master to...,start slave四件套

注意:

(1)master_host的ip地址改成s1的ip地址。

(2)如果要改为GTID复制,去掉master_log_file和master_log_pos参数,改成MASTER_AUTO_POSITION=1

stop slave;

change master to master_host='192.168.137.11',
MASTER_USER='repl',
MASTER_PASSWORD='Alice123!',
master_log_file='xxx', // 去master_host对应ip地址的mysql实例中使用"show master status;"获取
master_log_pos=xxx; // 去master_host对应ip地址的mysql实例中使用"show master status;"获取

start slave;

查看复制状态:

show slave status\G
7.测试同步

(1)主库写入测试数据

(2)从库查询数据

【三】级联改为一主两从(基于位点复制)

1.在s1获取master status的binlog文件和偏移量:
mysql> show master status\G
2.获取slave status
show slave status\G;
3.停止s1复制,再启动s1的复制
start slave;
4.重新配置s2的复制

注意:

(1)change master to中master_host改回master主库的ip地址

(2)下列语句是基于位点复制的,如果要改为GTID复制,需要去掉bin_log_file和bin_log_pos参数,添加MASTER_AUTO_POSITION=1

stop slave;

change master to master_host='192.168.137.2',
MASTER_USER='repl',
MASTER_PASSWORD='Alice123!',
master_log_file='xxx', // 去master_host对应ip地址的mysql实例中使用"show master status;"获取
master_log_pos=xxx; // 去master_host对应ip地址的mysql实例中使用"show master status;"获取

start slave;
城东书院 www.cdsy.xyz
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐