MySQL 之双主搭建

文章
林里克斯

两台 MySQL 互为主从,且两台 MySQL 均作为主节点对外提供服务;

MySQL 之双主搭建


试验平台:CentOS Linux release 7.6.1810

试验IP:MySQL0110.10.13.8;MySQL0210.10.13.9

MySQL Version:mysql 5.7.32



一、MySQL 安装


原理:

  • 当从库 IO 线程接受到主库传递来的二进制日志 (Binlog) 并将之保存为从库的中继日志 (relay log), 然后从库 SQL 线程将中继日志 (relay log) 的事件重做到从库上,实现主从数据同步

  • 如果 SQL 线程发现该事件的 server_id 与当前从库的 server_id 相同,则会丢弃该事件,因此如果两台
    MySQL 如何互为主从,不会导致相同的事件被重复执行。

1.下载 tar

$ wget https://mirrors.tuna.tsinghua.edu.cn/mysql/downloads/MySQL-5.7/mysql-5.7.32-el7-x86_64.tar.gz
#若链接失效,请自行下载相应版本的 tar 包即可

2.卸载自带 MariaDB

$ sudo yum -y remove mariadb-libs-5.5.60-1.el7_5.x86_64

3.解压安装

$ tar xf mysql-5.7.32-el7-x86_64.tar.gz
$ mv mysql-5.7.32-el7-x86_64 mysql
$ cd /data/mysql
$ mkdir /data/mysql/data
$ mkdir /data/mysql/logs
$ touch /data/mysql/my.cnf
$ bin/mysqld --defaults-file=/data/mysql/my.cnf --initialize --user=mysql --basedir=/data/mysql --datadir=/data/mysql/data
2020-12-22T23:19:19.228457Z 0 [Warning] Changed limits: max_open_files: 1024 (requested 5000)
2020-12-22T23:19:19.228686Z 0 [Warning] Changed limits: table_open_cache: 431 (requested 2000)
2020-12-22T23:19:19.229593Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2020-12-22T23:19:19.236604Z 0 [Warning] One can only use the --user switch if running as root

2020-12-22T23:19:19.885118Z 0 [Warning] InnoDB: New log files created, LSN=45790
2020-12-22T23:19:19.955592Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2020-12-22T23:19:20.077913Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 7b19cc97-4404-11eb-9ecc-005056272355.
2020-12-22T23:19:20.082285Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2020-12-22T23:19:20.821767Z 0 [Warning] CA certificate ca.pem is self signed.
2020-12-22T23:19:21.443982Z 1 [Note] A temporary password is generated for root@localhost: &lIj<>fg?72,

这里要注意下 --defaults-file=/data/mysql/my.cnf 这个参数的顺序,不然会有以下错误

$ bin/mysqld --initialize --user=mysql --basedir=/data/mysql --datadir=/data/mysql/data --defaults-file=/data/mysql/my.cnf
2020-12-22T22:56:22.192297Z 0 [ERROR] unknown variable 'defaults-file=/data/mysql/my.cnf'
#放后面识别不到这个参数

二、编写双主配置文件


1.Mysql01my.cnf

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

[mysqld]
join_buffer_size = 256K
query_cache_type = 0
max_heap_table_size = 32M

basedir = /data/mysql
port = 3306
socket = /data/mysql/mysql.sock
datadir = /data/mysql/data
pid-file = /data/mysql/logs/mysql.pid
log-error = /data/mysql/logs/mysql.err

lower_case_table_names=1
server_id = 1
auto_increment_offset = 1
auto_increment_increment = 2
log-bin = mysql-bin
binlog_format = mixed
max_binlog_size=1024M
expire_logs_days = 10

replicate-ignore-db = mysql
replicate-ignore-db = information_schema
replicate-ignore-db = performance_schema
relay_log=mysql-relay-bin
log-slave-updates=on

skip-external-locking
performance_schema_max_table_instances=400
table_definition_cache=400

max_allowed_packet = 100G
table_open_cache = 128
sort_buffer_size = 768K
net_buffer_length = 8K

thread_cache_size = 16
query_cache_size = 0M
tmp_table_size = 32M

explicit_defaults_for_timestamp = true
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

slow-query-log-file=/data/mysql/logs/mysql-slow.log
long_query_time=3
default_storage_engine = InnoDB
innodb_data_home_dir = /data/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /data/mysql/data
innodb_buffer_pool_size = 32M
innodb_log_file_size = 32M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 120
innodb_max_dirty_pages_pct = 90
innodb_read_io_threads = 1
innodb_write_io_threads = 1

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 32M
sort_buffer_size = 768K
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout

2.需要注意的几个配置项

server_id = 2
auto_increment_offset = 2
auto_increment_increment = 2

3.Mysql02my.cnf

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

[mysqld]
join_buffer_size = 256K
query_cache_type = 0
max_heap_table_size = 32M

basedir = /data/mysql
port = 3306
socket = /data/mysql/mysql.sock
datadir = /data/mysql/data
pid-file = /data/mysql/logs/mysql.pid
log-error = /data/mysql/logs/mysql.err

lower_case_table_names=1
server_id = 2
auto_increment_offset = 2
auto_increment_increment = 2
log-bin = mysql-bin
binlog_format = mixed
max_binlog_size=1024M
expire_logs_days = 10

replicate-ignore-db = mysql
replicate-ignore-db = information_schema
replicate-ignore-db = performance_schema
relay_log=mysql-relay-bin
log-slave-updates=on

skip-external-locking
performance_schema_max_table_instances=400
table_definition_cache=400

max_allowed_packet = 100G
table_open_cache = 128
sort_buffer_size = 768K
net_buffer_length = 8K

thread_cache_size = 16
query_cache_size = 0M
tmp_table_size = 32M

explicit_defaults_for_timestamp = true
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

slow-query-log-file=/data/mysql/logs/mysql-slow.log
long_query_time=3
default_storage_engine = InnoDB
innodb_data_home_dir = /data/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /data/mysql/data
innodb_buffer_pool_size = 32M
innodb_log_file_size = 32M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 120
innodb_max_dirty_pages_pct = 90
innodb_read_io_threads = 1
innodb_write_io_threads = 1

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 32M
sort_buffer_size = 768K
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout

三、启动 MySQL


1.增加环境变量

$ vim ~/.bashrc 
export PATH=/data/mysql/bin:/data/mysql/lib:$PATH

$ source ~/.bashrc

2.启动 mysql

$ cp -rp ./support-files/mysql.server mysqld.sh
$ sh mysqld.sh start

3.登录配置

$ mysql -u root -p
#这里密码输入初始化时给的临时密码
> ALTER USER 'root'@'localhost' IDENTIFIED BY 'redhat';ALTER USER 'root'@'localhost' IDENTIFIED BY 'redhat';

4.使用新密码登录测试

$ mysql -u root -predhat
#可以正常登陆即可

四、配置数据同步


1.MySQL01 创建给 MySQL02 同步的账号

> grant replication slave on *.* to 'repl'@'10.10.13.9' identified by 'qwe123';
> flush privileges;

2.MySQL02 创建给 MySQL01 同步的账号

> grant replication slave on *.* to 'repl'@'10.10.13.8' identified by 'qwe123';
> flush privileges;

3.配置同步信息

3.1 查看 MySQL01 信息

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

3.2 MySQL02 连接 MySQL01

> change master to master_host='10.10.13.8',master_port=3306,master_user='repl',master_password='qwe123',master_log_file='mysql-bin.000001',master_log_pos=857;

> start slave;

> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.10.13.8
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 857
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: mysql,information_schema,performance_schema
           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: 857
              Relay_Log_Space: 527
              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: 89526cc3-4405-11eb-b5b6-005056299372
             Master_Info_File: /data/mysql/data/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)

另外一台相同操作

3.3 查看 MySQL02 信息

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

3.4 MySQL01 连接 MySQL02

> change master to master_host='10.10.13.9',master_port=3306,master_user='repl',master_password='qwe123',master_log_file='mysql-bin.000001',master_log_pos=857;

> start slave;

> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.10.13.9
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 857
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: mysql,information_schema,performance_schema
           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: 857
              Relay_Log_Space: 527
              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: 2
                  Master_UUID: 7b19cc97-4404-11eb-9ecc-005056272355
             Master_Info_File: /data/mysql/data/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)

3.5 2 个库都是 Yes 即可

Slave_IO_Running: Yes
Slave_SQL_Running: Yes

五、验证


1.在 MySQL01 上创建 test1

> create database test1;

2.在 MySQL02 上查看库

> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test1              |
+--------------------+

3.在 MySQL02 上创建 test2

> create database test2;

4.在 MySQL01 上查看库

> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test1              |
| test2              |
+--------------------+

5.测试 表 的数据同步

> CREATE TABLE IF NOT EXISTS `jarbo`(
   `jarbo_id` INT UNSIGNED AUTO_INCREMENT,
   `title` VARCHAR(100) NOT NULL,
   `author` VARCHAR(40) NOT NULL,
   `date` DATE,
   PRIMARY KEY ( `jarbo_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
#创建一个测试表

> INSERT INTO jarbo (title, author, date) VALUES ("test", "Jarbo", NOW());
#插入一点数据

6.在另外个实例上查看

> select * from jarbo;
+----------+-------+--------+------------+
| jarbo_id | title | author | date       |
+----------+-------+--------+------------+
|        2 | test  | Jarbo  | 2020-12-22 |
+----------+-------+--------+------------+
#已经同步过去

后续再引入 keepalived 来实现高可用


Over~

版权协议须知!

本篇文章来源于 Uambiguous ,如本文章侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意

1232 0 2020-12-12


分享:
icon_mrgreen.gificon_neutral.gificon_twisted.gificon_arrow.gificon_eek.gificon_smile.gificon_confused.gificon_cool.gificon_evil.gificon_biggrin.gificon_idea.gificon_redface.gificon_razz.gificon_rolleyes.gificon_wink.gificon_cry.gificon_surprised.gificon_lol.gificon_mad.gificon_sad.gificon_exclaim.gificon_question.gif
博主卡片
林里克斯 博主大人
一个致力于Linux的运维平台
运维时间
搭建这个平台,只为分享及记载自己所遇之事和难题。

现在时间 2024-12-28

今日天气
站点统计
  • 文章总数:241篇
  • 分类总数:29个
  • 评论总数:12条
  • 本站总访问量 353819 次

@奥奥

@Wong arrhenius 牛比

@MakerFace 厉害了!