Centos7 MySQL8 部署 主从复制与MySQL-router实现读写分离及从库负载均衡

Centos7部署MySQL-router实现读写分离及从库负载均衡

环境:

iphostname部署服务
192.168.101.101mastermysql
192.168.101.102slave1mysql
192.168.101.103slave2mysql
192.168.101.104routermysql mysql-router

1. 安装MySQL

  1. 基础环境配置

    # 修改IP地址为固定ip(可选操作此处略)
    # 关闭防火墙
    $ systemctl stop firewalld
    $ systemctl disable firewalld
    
    # 在防火墙放行NTP协议
    $ firewall-cmd --add-service=ntp --permanent
    $ firewall-cmd --reload
    $ firewall-cmd --list-all
    
    # 关闭selinux
    $ setenforce 0
    
    # 修改主机名
    $ hostnamectl set-hostname master
    $ hostnamectl set-hostname slave1
    $ hostnamectl set-hostname slave2
    $ hostnamectl set-hostname router
    
  2. 修改hosts文件

    $ vim /etc/hosts
    192.168.101.101 master
    192.168.101.102 slave1
    192.168.101.103 slave2
    192.168.101.104 router
    
  3. 设置时间同步

    # 安装chrony (// krɑːnɪ //) 服务,各主机均安装
    $ yum install chrony
    $ systemctl enable chronyd.service 
    $ systemctl start chronyd.service
    
    # 配置master节点为时间服务器
    $ vim /etc/chrony.conf
    allow 192.168.101.0/24 #配置允许同步的网段 
    
    $ systemctl restart chronyd
    
    # 检查时间是否同步成功
    $ chronyc sources -v
    210 Number of sources = 4
    
      .-- Source mode  '^' = server, '=' = peer, '#' = local clock.
     / .- Source state '*' = current synced, '+' = combined , '-' = not combined,
    | /   '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
    ||                                                 .- xxxx [ yyyy ] +/- zzzz
    ||      Reachability register (octal) -.           |  xxxx = adjusted offset,
    ||      Log2(Polling interval) --.      |          |  yyyy = measured offset,
    ||                                \     |          |  zzzz = estimated error.
    ||                                 |    |           \
    MS Name/IP address         Stratum Poll Reach LastRx Last sample               
    ===============================================================================
    ^? ns2.customer-resolver.net     2   6     7     0   -790us[ -790us] +/-  154ms
    ^? ntp6.flashdance.cx            2   6     1     2    -55ms[  -55ms] +/-  268ms
    ^? electrode.felixc.at           3   6     3     2    +16ms[  +16ms] +/-  160ms
    ^? time.cloudflare.com           3   6     3     2    +64ms[  +64ms] +/-  187ms
    
    
    
    # 配置其它主机节点的时间服务器为master
    # 注释掉默认时间服务器,配置master为时间同步源
    $ vim /etc/chrony.conf
    # server 0.centos.pool.ntp.org iburst
    # server 1.centos.pool.ntp.org iburst
    # server 2.centos.pool.ntp.org iburst
    # server 3.centos.pool.ntp.org iburst
    server master iburst
    
    $ systemctl restart chronyd
    $ systemctl enable chronyd
    
    #查看同步manager时间成功 
    $ chronyc sources
    210 Number of sources = 1
    MS Name/IP address         Stratum Poll Reach LastRx Last sample               
    ===============================================================================
    ^? bogon                         4   6     3     0    +50ms[  +50ms] +/-  172ms
    
  4. 下载MySQL YUM仓库:

    $ wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
    
  5. 安装MySQL YUM仓库:

    $ rpm -Uvh mysql80-community-release-el7-3.noarch.rpm
    
    # 查看安装情况
    $ rpm -ql mysql80-community-release
    
  6. 安装数据库

    # 四个节点分别安装
    $ yum install mysql-server mysql -y
    $ yum install mysql-server mysql -y
    $ yum install mysql-server mysql -y
    $ yum install mysql-server mysql -y
    
  7. 启动数据库

    $ systemctl start mysqld
    
  8. 修改密码

    $ systemctl restart mysqld
    $ grep 'temporary password' /var/log/mysqld.log
    2021-03-04T02:30:35.218501Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: scAIUkhP&4Y&
    
    $ mysql -uroot -p'scAIUkhP&4Y&'
    
    > ALTER USER 'root'@'localhost' IDENTIFIED BY 'Ytl@2032734117';
    Query OK, 0 rows affected (0.00 sec)
    
    # 所有节点相同操作
    

2. 部署mysql-router

# router结点部署mysql-router
# 从官网下载rpm包

$ wget https://cdn.mysql.com//Downloads/MySQL-Router/mysql-router-community-8.0.23-1.el7.x86_64.rpm

$ yum localinstall mysql-router-community-8.0.23-1.el7.x86_64.rpm

2. 配置主从复制

master结点和两个bak结点配置主从复制

2.1 设置主库SERVER_ID和启动二进制日志

$ vim /etc/my.cnf 
[mysqld]
server_id=101  # 设置主服务器server_id
log_bin=/var/lib/mysql/binlogs/master
log_bin_index=/var/lib/mysql/binlogs/master.index

$ mkdir /var/lib/mysql/binlogs
$ chown -R mysql.mysql /var/lib/mysql/
$ systemctl restart mysqld

2.2 在主库中创建复制用户

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

> create user 'binlog_user'@'%' identified by '123456Abc!';
Query OK, 0 rows affected (0.01 sec)

> grant replication slave on *.* to 'binlog_user'@'%';
Query OK, 0 rows affected (0.01 sec)

# 四个节点全部设置root远程登录账号
> create user 'root'@'%' identified by 'Ytl@2032734117';
> grant all on *.* to 'root'@'%';

2.3 从库设置SERVER_ID

# slave1 节点

# server_id不能相同
$ vim /etc/my.cnf
server_id=102
log_bin=/var/lib/mysql/binlogs/slave1
log_bin_index=/var/lib/mysql/binlogs/slave1.index

# 重启服务
$ mkdir /var/lib/mysql/binlogs
$ chown -R mysql.mysql /var/lib/mysql/
$ systemctl restart mysqld


# slave2 节点
$ vim /etc/my.cnf
server_id=103
log_bin=/var/lib/mysql/binlogs/slave2
log_bin_index=/var/lib/mysql/binlogs/slave2.index
# 重启服务
$ mkdir /var/lib/mysql/binlogs
$ chown -R mysql.mysql /var/lib/mysql/
$ systemctl restart mysqld

2.4 设置同步

# master节点操作
> show master status; 
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| master.000001 |     1024 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

# 从节点操作
$ mysql -uroot -pYtl@2032734117

> change master to master_host='192.168.101.101',master_user='binlog_user',master_password='123456Abc!',master_log_file='master.000001', master_log_pos=1024,get_master_public_key=1;
Query OK, 0 rows affected, 9 warnings (0.01 sec)

> start slave;
Query OK, 0 rows affected, 1 warning (0.01 sec)

> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.101.101
                  Master_User: binlog_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master.000001
          Read_Master_Log_Pos: 1024
               Relay_Log_File: bak1-relay-bin.000002
                Relay_Log_Pos: 321
        Relay_Master_Log_File: master.000001
             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: 1024
              Relay_Log_Space: 529
              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: 101
                  Master_UUID: 994e44af-7c91-11eb-9c27-000c29a55f9e
             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 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: 
       Master_public_key_path: 
        Get_master_public_key: 1
            Network_Namespace: 
1 row in set, 1 warning (0.00 sec)

# 如果出现server_uuid错误:(比如克隆虚拟机做实验)
# 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_IO_Error:致命错误:由于主服务器和从服务器具有相等的MySQL服务器UUID,从服务器I / O线程停止。 这些UUID必须不同才能进行复制。
# 解决方法:
# 进入主库或从库的数据目录: 
[root@slave01 ~]$ cd /var/lib/mysql/
[root@slave01 mysql]$ cat auto.cnf 
[auto]
server-uuid=9a51e3b8-5d0b-11ea-8309-000c29ba741e
# 将其改名并重启服务即可生成新的server-uuid 
[root@slave01 mysql]$ mv auto.cnf auto.cnf.bak 
[root@slave01 mysql]$ systemctl restart mysqld



> change master to master_host='192.168.101.101',master_user='binlog_user',master_password='123456Abc!',master_log_file='master.000001', master_log_pos=1024,get_master_public_key=1;
Query OK, 0 rows affected, 9 warnings (0.03 sec)

> start slave;
Query OK, 0 rows affected, 1 warning (0.01 sec)
> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.101.101
                  Master_User: binlog_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master.000001
          Read_Master_Log_Pos: 1212
               Relay_Log_File: bak2-relay-bin.000002
                Relay_Log_Pos: 321
        Relay_Master_Log_File: master.000001
             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: 1212
              Relay_Log_Space: 529
              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: 101
                  Master_UUID: 994e44af-7c91-11eb-9c27-000c29a55f9e
             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 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: 
       Master_public_key_path: 
        Get_master_public_key: 1
            Network_Namespace: 
1 row in set, 1 warning (0.00 sec)

2.5 验证

# 主节点
> create database banks;
Query OK, 1 row affected (0.01 sec)

# 两个从节点
> show databases;
+--------------------+
| Database           |
+--------------------+
| banks              |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

3. 配置mysql-router

3.1 修改配置文件

$ vim /etc/mysqlrouter/mysqlrouter.conf
#添加高可用标签,配置master结点为写结点
[routing:failover]
bind_address = 0.0.0.0
bind_port = 7001
max_connections = 1024
mode = read-write
#实际MySQL地址
destinations = 192.168.101.101:3306

#轮询标签,从库进行负载均衡的轮询访问
[routing:balancing]
bind_address = 0.0.0.0
bind_port = 7002
max_connections = 1024
mode = read-only
#实际MySQL地址
destinations = 192.168.101.102:3306,192.168.101.103:3306

3.2 启动服务

$ systemctl start mysqlrouter.service
$ systemctl enable mysqlrouter.service

4. 验证测试

4.1 查看服务端口

# router节点
$ netstat -tnlp |grep mysql
tcp        0      0 0.0.0.0:7001            0.0.0.0:*               LISTEN      2848/mysqlrouter    
tcp        0      0 0.0.0.0:7002            0.0.0.0:*               LISTEN      2848/mysqlrouter    
tcp6       0      0 :::33060                :::*                    LISTEN      2667/mysqld         
tcp6       0      0 :::3306                 :::*                    LISTEN      2667/mysqld         

4.2 测试从库负载均衡

# router节点

# router节点远程连接其他节点的mysql,测试能否远程登录
$ mysql -uroot -pYtl@2032734117 -h192.168.101.101 -P3306
$ mysql -uroot -pYtl@2032734117 -h192.168.101.102 -P3306
$ mysql -uroot -pYtl@2032734117 -h192.168.101.103 -P3306

# 成功连接后连接后操作的是master主节点
$ mysql -u root -h 192.168.101.104 -p'Ytl@2032734117' -P 7001
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 60
Server version: 8.0.23 MySQL Community Server - GPL

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

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           |
+--------------------+
| banks              |
| information_schema |
| mysql              |
| performance_schema |
| sss                |
| sys                |
+--------------------+
6 rows in set (0.03 sec)


# 成功连接后操作的是slave1或slave2随机使用
$ mysql -u root -h 192.168.101.104 -p'Ytl@2032734117' -P 7002
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 22
Server version: 8.0.23 MySQL Community Server - GPL

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

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           |
+--------------------+
| banks              |
| information_schema |
| mysql              |
| performance_schema |
| sss                |
| sys                |
+--------------------+
6 rows in set (0.00 sec)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值