数据库笔记-1

数据库笔记-1

0.msyql8.0.32或5.7(二进制安装)
一.安装数据库(编译-二进制)

1、创建用户
[root@mysqlmaster~]# groupadd mysql
[root@mysqlmaster~]# useradd -r -g mysql -s /usr/sbin/nologin mysql
2、创建目录
[root@mysqlmaster~]# mkdir /data/mysql -p
[root@mysqlmaster~]# chown -R mysql.mysql /data/mysql
3、准备二进制程序


[root@mysqlmaster~]# wget https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.32-linux-glibc2.12-x86_64.tar
或
wget https://cdn.mysql.com/archives/mysql-5.6/mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz


--2023-06-07 10:54:29--  https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.32-linux-glibc2.12-x86_64.tar
正在解析主机 cdn.mysql.com (cdn.mysql.com)... 104.70.237.54
正在连接 cdn.mysql.com (cdn.mysql.com)|104.70.237.54|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1005660160 (959M) [application/x-tar]
正在保存至: “mysql-8.0.32-linux-glibc2.12-x86_64.tar”

100%[====================================================================================================>] 1,005,660,160 26.6MB/s 用时 29s    

2023-06-07 10:54:58 (32.8 MB/s) - 已保存 “mysql-8.0.32-linux-glibc2.12-x86_64.tar” [1005660160/1005660160])

[root@mysqlmaster~]# tar xvf mysql-8.0.32-linux-glibc2.12-x86_64.tar
tar zxvf mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz

mysql-test-8.0.32-linux-glibc2.12-x86_64.tar.xz
mysql-8.0.32-linux-glibc2.12-x86_64.tar.xz
mysql-router-8.0.32-linux-glibc2.12-x86_64.tar.xz

[root@mysqlmaster~]#tar xf mysql-8.0.32-linux-glibc2.12-x86_64.tar.xz -C /usr/local/
[root@mysqlmaster~]# cd /usr/local
[root@node-centos7-70 local]# ln -sv mysql-8.0.32-linux-glibc2.12-x86_64 mysql
"mysql" -> "mysql-8.0.32-linux-glibc2.12-x86_64"


4、安装依赖包
[root@mysqlmaster~]# yum install -y libaio numactl-libs
5、设置PATH环境变量
[root@mysqlmaster~]# echo "PATH=/usr/local/mysql/bin:$PATH" > /etc/profile.d/mysql.sh
[root@mysqlmaster~]# . /etc/profile.d/mysql.sh
6、创建配置文件


[root@mysqlmaster~]# tee > /etc/my.cnf << EOF
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
pid-file=/data/mysql/mysql.pid
log-error=/data/mysql/mysql.log

[client]
socket=/data/mysql/mysql.sock
EOF


7、创建数据库文件,并提取root密码


[root@mysqlmaster~]# mysqld --initialize --user=mysql --datadir=/data/mysql
[root@mysqlmaster~]# grep password /data/mysql/mysql.log
2023-06-07T03:20:09.342795Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: ,*9LyAr6wrr#
[root@mysqlmaster~]# awk '/temporary password/{print $NF}' /data/mysql/mysql.log 
,*9LyAr6wrr#


8、创建服务脚本,并启动服务
[root@mysqlmaster~]# cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@mysqlmaster~]# chkconfig --add mysqld
[root@mysqlmaster~]# service mysqld start
Starting MySQL... SUCCESS! 
9、修改初始密码,测试访问数据库

mysql(master)
sJDiAp3,stla


mysql(slave)
Mi*tYko=d7ZJ


mysqladmin -uroot -p'EjJuF5hUQa:r' password 'mysql'

mysqladmin -uroot -p'p?vfl2d_iE5l' password 'mysql'

[root@mysqlmaster~]# mysqladmin -uroot -p',*9LyAr6wrr#' password 'mysql'
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
[root@mysqlmaster~]# mysql -uroot -pmysql
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 9
Server version: 8.0.32 MySQL Community Server - GPL

Copyright (c) 2000, 2023, 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           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> 

1.mysql主从同步原理

1. 在master上开启bin-log日志功能,记录更新、插入、删除的语句
2.必须开启三个线程,主上开启io线程,从上开启io线程和sql线程
3.从上io线程去连接master,master通过io线程检查有slave过来的请求,请求日志、postsion位置
4.master将这些相应的日志返回给slave,slave自己去下载本地的realy——log里面,写入一个master-info日志记录同步的点
5.slave的sql线程检查到realy-log日志有更新,然后在本地区exec执行





2.数据库密码忘记(解决)

ln -s /data/mysql/bin/mysql /bin/mysql

软连接成功 现在进入数据库可以用
mysql -uroot -p


01 停止数据库

02 特殊方式启动 修改密码

03 停止 重新正常启动


学会了这个密码重置 在公司能直接开干吗? 能不能上去直接停止数据库呢?

不可以

正确流程:没有用户访问量时 ------一般建议夜里1点
做个报错页面  比如 502 500 跳转  服务器维护中



2.mysql主从配置

环境:虚拟机
MySQL(主) 10.0.1.154
mysql(从) 10.0.1.155




一.安装数据库(编译-二进制)

1、创建用户
[root@mysqlmaster~]# groupadd mysql
[root@mysqlmaster~]# useradd -r -g mysql -s /usr/sbin/nologin mysql
2、创建目录
[root@mysqlmaster~]# mkdir /data/mysql -p
[root@mysqlmaster~]# chown -R mysql.mysql /data/mysql
3、准备二进制程序


[root@mysqlmaster~]# wget https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.32-linux-glibc2.12-x86_64.tar
或
wget https://cdn.mysql.com/archives/mysql-5.6/mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz


--2023-06-07 10:54:29--  https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.32-linux-glibc2.12-x86_64.tar
正在解析主机 cdn.mysql.com (cdn.mysql.com)... 104.70.237.54
正在连接 cdn.mysql.com (cdn.mysql.com)|104.70.237.54|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1005660160 (959M) [application/x-tar]
正在保存至: “mysql-8.0.32-linux-glibc2.12-x86_64.tar”

100%[====================================================================================================>] 1,005,660,160 26.6MB/s 用时 29s    

2023-06-07 10:54:58 (32.8 MB/s) - 已保存 “mysql-8.0.32-linux-glibc2.12-x86_64.tar” [1005660160/1005660160])

[root@mysqlmaster~]# tar xvf mysql-8.0.32-linux-glibc2.12-x86_64.tar
tar zxvf mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz

mysql-test-8.0.32-linux-glibc2.12-x86_64.tar.xz
mysql-8.0.32-linux-glibc2.12-x86_64.tar.xz
mysql-router-8.0.32-linux-glibc2.12-x86_64.tar.xz

[root@mysqlmaster~]#tar xf mysql-8.0.32-linux-glibc2.12-x86_64.tar.xz -C /usr/local/
[root@mysqlmaster~]# cd /usr/local
[root@node-centos7-70 local]# ln -sv mysql-8.0.32-linux-glibc2.12-x86_64 mysql
"mysql" -> "mysql-8.0.32-linux-glibc2.12-x86_64"


4、安装依赖包
[root@mysqlmaster~]# yum install -y libaio numactl-libs
5、设置PATH环境变量
[root@mysqlmaster~]# echo "PATH=/usr/local/mysql/bin:$PATH" > /etc/profile.d/mysql.sh
[root@mysqlmaster~]# . /etc/profile.d/mysql.sh
6、创建配置文件


[root@mysqlmaster~]# tee > /etc/my.cnf << EOF
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
pid-file=/data/mysql/mysql.pid
log-error=/data/mysql/mysql.log

[client]
socket=/data/mysql/mysql.sock
EOF


7、创建数据库文件,并提取root密码


[root@mysqlmaster~]# mysqld --initialize --user=mysql --datadir=/data/mysql
[root@mysqlmaster~]# grep password /data/mysql/mysql.log
2023-06-07T03:20:09.342795Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: ,*9LyAr6wrr#
[root@mysqlmaster~]# awk '/temporary password/{print $NF}' /data/mysql/mysql.log 
,*9LyAr6wrr#


8、创建服务脚本,并启动服务
[root@mysqlmaster~]# cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@mysqlmaster~]# chkconfig --add mysqld
[root@mysqlmaster~]# service mysqld start
Starting MySQL... SUCCESS! 
9、修改初始密码,测试访问数据库

mysql(master)
sJDiAp3,stla


mysql(slave)
Mi*tYko=d7ZJ


mysqladmin -uroot -p'EjJuF5hUQa:r' password 'mysql'

mysqladmin -uroot -p'p?vfl2d_iE5l' password 'mysql'

[root@mysqlmaster~]# mysqladmin -uroot -p',*9LyAr6wrr#' password 'mysql'
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
[root@mysqlmaster~]# mysql -uroot -pmysql
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 9
Server version: 8.0.32 MySQL Community Server - GPL

Copyright (c) 2000, 2023, 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           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> 





9.重启安装(查看服务)
service mysqld start
service mysqld stop
ss-tulpn




二.主库配置

mysql -uroot -pmysql
mysql -uroot -pmysql
1.关闭防火墙
开放指定的3306端口号(生产环境当中建议开放指定端口)
firewall-cmd --zone=public --add-port=3306/tcp -permanent
firewall-cmd -reload

关闭服务器的防火墙
systemctl stop firewalld
systemctl disable firewalld

2.配置主库文件信息



vim /etc/my.cnf
log-bin = mysql-bin  #开启binlog日志
server-id=1    #默认为1 不能一样
read-only=0    #1代表只读,0代表读写
binlog-ignore-db=mysql   #忽略的数据库 指不需要同步的数据库
binlog_format=mixed    #设定MySQL二进制日志记录事务的方式,此处采用智能混合格式,根据事务特性自动选择最优方式。
expire_logs_days=10   #设置MySQL二进制日志文件在10天后自动清除,以释放存储空间。

log-bin = mysql-bin
server-id=1
read-only=0 
binlog-ignore-db=mysql
binlog_format=mixed
expire_logs_days=10




#重启数据库
service mysql restart 



3.登录数据库-创建远程连接的账号--并授予主从复制权限(主库)
#登录mysql
mysql -uroot -pmysql
#创建nwq用户,并设置密码,该用户可在任意主机连接改mysql服务
CREATE USER 'nwq'@'%' IDENTIFIED WITH mysql_native_password BY 'Root@123456';

#为nwq用户分配主从复制权限
GRANT REPLICATION SLAVE ON *.* TO 'nwq'@'%';


#查看二进制日志坐标
show master status;

mysql> show master status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000004 |      658 |              | mysql            |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)



4.从库配置

vim /etc/my.cnf

log-bin = mysql-bin
server-id=11

#super-read-only (设置超级管理员页只读)--非必要

#重启数据库
service mysql restart 


5.登录数据库--设置从库配置(从库)
#登录mysql
mysql -uroot -pmysql

#mysql5.7以前版本
CHANGE MASTER TO
    MASTER_HOST='X',
    MASTER_USER='X',
    MASTER_PASSWORD='XI',
    MASTER_LOG_FILE='XY',
    MASTER_LOG_POS=X;
    
    #mysql8.0以上版本
    CHANGE REPLICATION SOURCE TO 
    SOURCE_HOST='X',         #主库ip地址
    SOURCE_USER='X',       #连接数据库的用户名
    SOURCE_PASSWORD='XI',   #连接主库的密码
    RELAY_LOG_FILE='XY', #--binlog日志文件名 注意:这里应该是RELAY_LOG_FILE而不是MASTER_LOG_FILE,因为后者是主库的设置项
    RELAY_LOG_POS=X; #--binlog日志文件位置 同样,应使用RELAY_LOG_POS来指定中继日志的位置
    
 
 
 #执行这段(我的mysql是8.0.32版本)
CHANGE REPLICATION SOURCE TO
    SOURCE_HOST='10.0.1.154',
    SOURCE_USER='nwq',
    SOURCE_PASSWORD='Root@123456',
    SOURCE_LOG_FILE='mysql-bin.000001',
    SOURCE_LOG_POS=1784;
    
    
6.启动复制进程
start slave;


7.查看从库是否成功与主库同步状态
#show slave status\G;

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for source to send event
                  Master_Host: 10.0.1.154
                  Master_User: nwq
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: binlog.000004
          Read_Master_Log_Pos: 658
               Relay_Log_File: centos7mage-relay-bin.000002
                Relay_Log_Pos: 323
        Relay_Master_Log_File: binlog.000004
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes



8.测试
#主库数据库

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

#从库数据库
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)
    
    
#创建数据库(主库)---看从库是否有
主库(创建数据库)
mysql> create database jpress;
Query OK, 1 row affected (0.01 sec)

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


从库:
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| jpress             |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

    
    
    
    
    


    

3.mysql主从故障案例解决




**mysql主从同步导致1062和1032问题**

**事情起因****mysql主从同步导致1062和1032问题**

1005  创建表失败
1006  创建数据库失败
1007  数据库已存在,创建数据库失败
1008  数据库不存在,删除数据库失败
1009  不能删除数据库文件导致删除数据库失败
1010  不能删除数据目录导致删除数据库失败

1064 sql语句语法错误(一定错了,不然不肯报错)
1380 sql语句复制错误(检查复制语句)
1062 尝试插入的记录与表中已有的记录有重复的唯一键值
1032 找不到记录(通常发生在尝试更新或删除数据库中不存在的记录时。解决方法是检查你的查询条件是否正确,确保你操作的数据实际存在于数据库中)

2003 此错误一般是配置主主时,没有同步造成的,stop slave; start slave;
1410 
1045  一般是主服务器没有给权限问题
mysql> GRANT REPLICATION SLAVE ON *.* TO 'nwq'@'%';
Query OK, 0 rows affected (0.01 sec)
1396 

1236 最好是重新设置主从问题
1.停掉数据库状态-----stop slave;
2.重新设置从库信息-------reset slave all;
3.重新配置master信息----CHANGE MASTER TO
  MASTER_HOST='10.0.1.154',
  MASTER_USER='nwq',
  MASTER_PASSWORD='Hello123',
  MASTER_PORT=3306,
  MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=22454520;
4.启用数据库状态--------start slave;)





#故障案例

案例1
 Last_Error: Coordinator stopped because there were error(s) in the worker(s). The most recent failure being: Worker 1 failed executing transaction 'ANONYMOUS' at master log binlog.000004, end_log_pos 849. See error log and/or performance_schema.replication_applier_status_by_worker table for more details about this failure or others, if any.

   
   
   
   
 案例2  
    
    Last_IO_Errno: 2003
                Last_IO_Error: error reconnecting to master 'nwq@10.0.1.154:3306' - retry-time: 60 retries: 1 message: Can't connect to MySQL server on '10.0.1.154:3306' (111)

解决:
此错误一般是配置主主时,没有同步造成的,stop slave; start slave;







案例3

                Last_IO_Errno: 13117
                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.


解决:
select uuid();

vim /data/mysql/auto.cnf
[auto]
server-uuid=ef681aa1-f979-11ee-87da-000c2924ffe2 # 按照这个16进制格式,修改server-uuid,重启mysql即可




案例4       
Last_SQL_Error: Coordinator stopped because there were error(s) in the worker(s). The most recent failure being: Worker 1 failed executing transaction 'ANONYMOUS' at master log mysql-bin.000001, end_log_pos 1502. See error log and/or performance_schema.replication_applier_status_by_worker table for more details about this failure or others, if any.



解决:
On master database:
mysql> reset master;
On slave database:
mysql> stop slave;
mysql> reset slave;
mysql> reset master;
mysql> start slave;








案例5
[root@centos7mage ~]# masterha_check_repl  --conf=/etc/mha/app1.cnf
Sun Apr 14 14:44:49 2024 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Sun Apr 14 14:44:49 2024 - [info] Reading application default configuration from /etc/mha/app1.cnf..
Sun Apr 14 14:44:49 2024 - [info] Reading server configuration from /etc/mha/app1.cnf..
Sun Apr 14 14:44:49 2024 - [info] MHA::MasterMonitor version 0.58.
Sun Apr 14 14:44:50 2024 - [info] GTID failover mode = 0
Sun Apr 14 14:44:50 2024 - [info] Dead Servers:
Sun Apr 14 14:44:50 2024 - [info] Alive Servers:
Sun Apr 14 14:44:50 2024 - [info]   10.0.1.154(10.0.1.154:3306)
Sun Apr 14 14:44:50 2024 - [info]   10.0.1.155(10.0.1.155:3306)
Sun Apr 14 14:44:50 2024 - [info]   10.0.1.156(10.0.1.156:3306)
Sun Apr 14 14:44:50 2024 - [info] Alive Slaves:
Sun Apr 14 14:44:50 2024 - [info]   10.0.1.155(10.0.1.155:3306)  Version=5.7.29-log (oldest major version between slaves) log-bin:enabled
Sun Apr 14 14:44:50 2024 - [info]     Replicating from 10.0.1.154(10.0.1.154:3306)
Sun Apr 14 14:44:50 2024 - [info]   10.0.1.156(10.0.1.156:3306)  Version=5.7.29-log (oldest major version between slaves) log-bin:enabled
Sun Apr 14 14:44:50 2024 - [info]     Replicating from 10.0.1.154(10.0.1.154:3306)
Sun Apr 14 14:44:50 2024 - [info] Current Alive Master: 10.0.1.154(10.0.1.154:3306)
Sun Apr 14 14:44:50 2024 - [info] Checking slave configurations..
Sun Apr 14 14:44:50 2024 - [info]  read_only=1 is not set on slave 10.0.1.155(10.0.1.155:3306).
Sun Apr 14 14:44:50 2024 - [warning]  relay_log_purge=0 is not set on slave 10.0.1.155(10.0.1.155:3306).
Sun Apr 14 14:44:50 2024 - [info]  read_only=1 is not set on slave 10.0.1.156(10.0.1.156:3306).
Sun Apr 14 14:44:50 2024 - [warning]  relay_log_purge=0 is not set on slave 10.0.1.156(10.0.1.156:3306).
Sun Apr 14 14:44:50 2024 - [info] Checking replication filtering settings..
Sun Apr 14 14:44:50 2024 - [info]  binlog_do_db= , binlog_ignore_db= mysql
Sun Apr 14 14:44:50 2024 - [error][/usr/share/perl5/vendor_perl/MHA/ServerManager.pm, ln443] Binlog filtering check failed on 10.0.1.155(10.0.1.155:3306)! All log-bin enabled servers must have same binlog filtering rules (same binlog-do-db and binlog-ignore-db). Check SHOW MASTER STATUS output and set my.cnf correctly.
Sun Apr 14 14:44:50 2024 - [warning] Bad Binlog/Replication filtering rules:
10.0.1.154 (current_master)
  Binlog_Do_DB: 
  Binlog_Ignore_DB: mysql
  Replicate_Do_DB: 
  Replicate_Ignore_DB: 
  Replicate_Do_Table: 
  Replicate_Ignore_Table: 
  Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 

10.0.1.155
  Binlog_Do_DB: 
  Binlog_Ignore_DB: 
  Replicate_Do_DB: 
  Replicate_Ignore_DB: 
  Replicate_Do_Table: 
  Replicate_Ignore_Table: 
  Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 

10.0.1.156
  Binlog_Do_DB: 
  Binlog_Ignore_DB: 
  Replicate_Do_DB: 
  Replicate_Ignore_DB: 
  Replicate_Do_Table: 
  Replicate_Ignore_Table: 
  Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 

Sun Apr 14 14:44:50 2024 - [error][/usr/share/perl5/vendor_perl/MHA/MasterMonitor.pm, ln359] Slave configurations is not valid.
Sun Apr 14 14:44:50 2024 - [error][/usr/share/perl5/vendor_perl/MHA/MasterMonitor.pm, ln427] Error happened on checking configurations.  at /usr/bin/masterha_check_repl line 48.
Sun Apr 14 14:44:50 2024 - [error][/usr/share/perl5/vendor_perl/MHA/MasterMonitor.pm, ln525] Error happened on monitoring servers.
Sun Apr 14 14:44:50 2024 - [info] Got exit code 1 (Not master dead).







原因:
针对日志中提到的问题,您可以按照以下步骤解决:

1. 设置从库为只读模式:

   [mysqld]
   read_only = 1
   

   修改后,需要重启MySQL服务使配置生效。

2. 调整relay_log_purge参数:
   将`relay_log_purge`设置为1,以保持relay日志的合理管理。同样在配置文件中添加或修改:

   ini
   [mysqld]
   relay_log_purge = 1
   

   重启MySQL服务以应用该变更。

3. 统一复制过滤规则:
   根据日志信息,主库(10.0.1.154)设置了`binlog-ignore-db=mysql`,而从库(10.0.1.155和10.0.1.156)没有设置这一项。为了保持一致性,您需要在从库上也设置相同的过滤规则,或者在主库上移除这一规则以保持所有服务器的日志过滤规则一致。在从库的配置文件中添加如下行:

   [mysqld]
   binlog-ignore-db=mysql
   

   再次强调,所有涉及MySQL配置文件的修改都需要重启MySQL服务以使其生效。


解决:
删除vim /etc/my.cnf
read_only = 1



添加从库1 从库2
binlog-ignore-db=mysql






故障六
[root@centos7mage mha]# masterha_check_repl  --conf=/etc/mha/app1.cnf
Sun Apr 14 15:09:33 2024 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Sun Apr 14 15:09:33 2024 - [info] Reading application default configuration from /etc/mha/app1.cnf..
Sun Apr 14 15:09:33 2024 - [info] Reading server configuration from /etc/mha/app1.cnf..
Sun Apr 14 15:09:33 2024 - [info] MHA::MasterMonitor version 0.58.
Sun Apr 14 15:09:34 2024 - [error][/usr/share/perl5/vendor_perl/MHA/ServerManager.pm, ln653] There are 2 non-slave servers! MHA manages at most one non-slave server. Check configurations.
Sun Apr 14 15:09:34 2024 - [error][/usr/share/perl5/vendor_perl/MHA/MasterMonitor.pm, ln427] Error happened on checking configurations.  at /usr/share/perl5/vendor_perl/MHA/MasterMonitor.pm line 329.
Sun Apr 14 15:09:34 2024 - [error][/usr/share/perl5/vendor_perl/MHA/MasterMonitor.pm, ln525] Error happened on monitoring servers.
Sun Apr 14 15:09:34 2024 - [info] Got exit code 1 (Not master dead).

MySQL Replication Health is NOT OK!







解决方法:

配置原先二个从库节点mysql为新的slave,并启动同步进程

mysql> reset master;
mysql> change master to CHANGE MASTER TO
    MASTER_HOST='10.0.1.154',
    MASTER_USER='nwq',
    MASTER_PASSWORD='Hello123',
    MASTER_LOG_FILE='mysql-bin.000009',
    MASTER_LOG_POS=154;
Query OK, 0 rows affected, 2 warnings (0.08 sec)


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





故障七
                Last_IO_Errno: 1236
                Last_IO_Error: Got fatal error 1236 from master when reading data from binary log: 'Client requested master to start replication from position > file size'



解决
1.停掉数据库状态-----stop slave;
2.重新设置从库信息-------reset slave all;
3.重新配置master信息----CHANGE MASTER TO
  MASTER_HOST='10.0.1.154',
  MASTER_USER='nwq',
  MASTER_PASSWORD='Hello123',
  MASTER_PORT=3306,
  MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=22454520;
4.启用数据库状态--------start slave;)

















排查思路
01 百度
02 查看错误代码
03 查看日志

04、网络不通  
05、密码不对  
06、pos不对


show slave status;
stop slave;
SET GLOBAL sql_slave_skip_counter = 1007;
start slave;

解决方式:在my.cnf文件中加入如下代码到[mysqld]。重启mysql

![img](file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml18884\wps1.jpg)

4.mysql一主二从

环境:虚拟机
主:10.0.1.154
从1:10.0.1.155
从2:10.0.1.156


一.安装数据库(编译-二进制)

1、创建用户
[root@mysqlmaster~]# groupadd mysql
[root@mysqlmaster~]# useradd -r -g mysql -s /usr/sbin/nologin mysql
2、创建目录
[root@mysqlmaster~]# mkdir /data/mysql -p
[root@mysqlmaster~]# chown -R mysql.mysql /data/mysql
3、准备二进制程序


[root@mysqlmaster~]# wget https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.32-linux-glibc2.12-x86_64.tar
或
wget https://cdn.mysql.com/archives/mysql-5.6/mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz


--2023-06-07 10:54:29--  https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.32-linux-glibc2.12-x86_64.tar
正在解析主机 cdn.mysql.com (cdn.mysql.com)... 104.70.237.54
正在连接 cdn.mysql.com (cdn.mysql.com)|104.70.237.54|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1005660160 (959M) [application/x-tar]
正在保存至: “mysql-8.0.32-linux-glibc2.12-x86_64.tar”

100%[====================================================================================================>] 1,005,660,160 26.6MB/s 用时 29s    

2023-06-07 10:54:58 (32.8 MB/s) - 已保存 “mysql-8.0.32-linux-glibc2.12-x86_64.tar” [1005660160/1005660160])

[root@mysqlmaster~]# tar xvf mysql-8.0.32-linux-glibc2.12-x86_64.tar
tar zxvf mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz

mysql-test-8.0.32-linux-glibc2.12-x86_64.tar.xz
mysql-8.0.32-linux-glibc2.12-x86_64.tar.xz
mysql-router-8.0.32-linux-glibc2.12-x86_64.tar.xz

[root@mysqlmaster~]#tar xf mysql-8.0.32-linux-glibc2.12-x86_64.tar.xz -C /usr/local/
[root@mysqlmaster~]# cd /usr/local
[root@node-centos7-70 local]# ln -sv mysql-8.0.32-linux-glibc2.12-x86_64 mysql
"mysql" -> "mysql-8.0.32-linux-glibc2.12-x86_64"


4、安装依赖包
[root@mysqlmaster~]# yum install -y libaio numactl-libs
5、设置PATH环境变量
[root@mysqlmaster~]# echo "PATH=/usr/local/mysql/bin:$PATH" > /etc/profile.d/mysql.sh
[root@mysqlmaster~]# . /etc/profile.d/mysql.sh
6、创建配置文件


[root@mysqlmaster~]# tee > /etc/my.cnf << EOF
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
pid-file=/data/mysql/mysql.pid
log-error=/data/mysql/mysql.log

[client]
socket=/data/mysql/mysql.sock
EOF


7、创建数据库文件,并提取root密码


[root@mysqlmaster~]# mysqld --initialize --user=mysql --datadir=/data/mysql
[root@mysqlmaster~]# grep password /data/mysql/mysql.log
2023-06-07T03:20:09.342795Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: ,*9LyAr6wrr#
[root@mysqlmaster~]# awk '/temporary password/{print $NF}' /data/mysql/mysql.log 
,*9LyAr6wrr#


8、创建服务脚本,并启动服务
[root@mysqlmaster~]# cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@mysqlmaster~]# chkconfig --add mysqld
[root@mysqlmaster~]# service mysqld start
Starting MySQL... SUCCESS! 
9、修改初始密码,测试访问数据库

mysql(master)
sJDiAp3,stla


mysql(slave)
Mi*tYko=d7ZJ


mysqladmin -uroot -p'ODq06w:4FwzO' password 'mysql'

mysqladmin -uroot -p'p?vfl2d_iE5l' password 'mysql'

[root@mysqlmaster~]# mysqladmin -uroot -p',*9LyAr6wrr#' password 'mysql'
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
[root@mysqlmaster~]# mysql -uroot -pmysql
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 9
Server version: 8.0.32 MySQL Community Server - GPL

Copyright (c) 2000, 2023, 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           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> 





9.重启安装(查看服务)
service mysqld start
service mysqld stop
ss-tulpn




二.主库配置

mysql -uroot -pmysql
mysql -uroot -pmysql
1.关闭防火墙
开放指定的3306端口号(生产环境当中建议开放指定端口)
firewall-cmd --zone=public --add-port=3306/tcp -permanent
firewall-cmd -reload

关闭服务器的防火墙
systemctl stop firewalld
systemctl disable firewalld

2.配置主库文件信息



vim /etc/my.cnf
log-bin = mysql-bin  #开启binlog日志
server-id=1    #默认为1 不能一样
read-only=0    #1代表只读,0代表读写
binlog-ignore-db=mysql   #忽略的数据库 指不需要同步的数据库
binlog_format=mixed    #设定MySQL二进制日志记录事务的方式,此处采用智能混合格式,根据事务特性自动选择最优方式。
expire_logs_days=10   #设置MySQL二进制日志文件在10天后自动清除,以释放存储空间。

#重启数据库
service mysql restart 



3.登录数据库-创建远程连接的账号--并授予主从复制权限
#登录mysql
mysql -uroot -pmysql
#创建nwq用户,并设置密码,该用户可在任意主机连接改mysql服务
CREATE USER 'nwq'@'%' IDENTIFIED WITH mysql_native_password BY 'Root@123456';

#为nwq用户分配主从复制权限
GRANT REPLICATION SLAVE ON *.* TO 'nwq'@'%';
flush privileges;


#查看二进制日志坐标
show master status;

mysql> show master status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000004 |      658 |              | mysql            |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)



4.从库配置(从库1/2)

vim /etc/my.cnf

从库1
log-bin = mysql-bin
server-id=11

从库2
log-bin = mysql-bin
server-id=12

#super-read-only (设置超级管理员页只读)--非必要

#重启数据库
service mysql restart 


5.登录数据库--设置主库配置
#登录mysql
mysql -uroot -pmysql

#mysql5.7以前版本
CHANGE MASTER TO
    MASTER_HOST='X',
    MASTER_USER='X',
    MASTER_PASSWORD='XI',
    MASTER_LOG_FILE='XY',
    MASTER_LOG_POS=X;
    
    #mysql8.0以上版本
    CHANGE REPLICATION SOURCE TO 
    SOURCE_HOST='X',         #主库ip地址
    SOURCE_USER='X',       #连接数据库的用户名
    SOURCE_PASSWORD='XI',   #连接主库的密码
    RELAY_LOG_FILE='XY', #--binlog日志文件名 注意:这里应该是RELAY_LOG_FILE而不是MASTER_LOG_FILE,因为后者是主库的设置项
    RELAY_LOG_POS=X; #--binlog日志文件位置 同样,应使用RELAY_LOG_POS来指定中继日志的位置
    
 
 
 #执行这段(我的mysql是8.0.32版本)从库1
CHANGE REPLICATION SOURCE TO
    SOURCE_HOST='10.0.1.154',
    SOURCE_USER='nwq',
    SOURCE_PASSWORD='Root@123456',
    SOURCE_LOG_FILE='mysql-bin.000001',
    SOURCE_LOG_POS=825;
    
    
    #从库2
    CHANGE REPLICATION SOURCE TO
    SOURCE_HOST='10.0.1.154',
    SOURCE_USER='nwq',
    SOURCE_PASSWORD='Root@123456',
    SOURCE_LOG_FILE='mysql-bin.000003',
    SOURCE_LOG_POS=658;
    
   
  # tips:当配置第二个或多个从的时候,一定要再重新获取主的binlog文件名和binlog文件位置
  
   
   
6.启动复制进程(从库1/2)
start slave;


7.查看从库是否成功与主库同步状态
#show slave status\G;

#从库1状态
mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for source to send event
                  Master_Host: 10.0.1.154
                  Master_User: nwq
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: binlog.000004
          Read_Master_Log_Pos: 658
               Relay_Log_File: centos7mage-relay-bin.000002
                Relay_Log_Pos: 323
        Relay_Master_Log_File: binlog.000004
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes



#从库2状态
mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for source to send event
                  Master_Host: 10.0.1.154
                  Master_User: nwq
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: binlog.000004
          Read_Master_Log_Pos: 849
               Relay_Log_File: centos7mage-relay-bin.000002
                Relay_Log_Pos: 514
        Relay_Master_Log_File: binlog.000004
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes




8.测试
#主库数据库

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

#从库数据库
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)
    
    
#创建数据库(主库)---看从库是否有
主库(创建数据库)
mysql> create database kaige;
Query OK, 1 row affected (0.00 sec)

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



从库1:
Query OK, 0 rows affected, 1 warning (0.00 sec)

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


从库2:
mysql> start slave;
Query OK, 0 rows affected, 1 warning (0.00 sec)

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








5.mysql主主模式--(互为主从--一般结合高可用(keepalived))

#步骤

环境:虚拟机

主1:10.0.1.154
主2:10.0.1.155

#tips:此前已做过主从配置,现在只需要把把从变为主-互为主从就可以了


1. 在主服务器上配置 /etc/my.cnf 文件,配置如下:(主1)
log-bin=mysql-bin
server-id=1
read-only=0 
binlog-ignore-db=mysql
binlog_format=mixed
expire_logs_days=10
auto_increment_increment=2   #步进值auto_imcrement。一般有n台主MySQL就填n
auto_increment_offset=1   #起始值。一般填第n台主MySQL。此时为第二台主MySQL



2.在从服务器上配置 /etc/my.cnf 文件,配置如下(主2)
log-bin=mysql-bin
server-id=2
read-only=0 
auto-increment-offset=2
auto-increment-increment=2




3.重启服务(主1主2)
service mysql restart





4.授权账户--密码(主2)

CREATE USER 'nwq'@'%' IDENTIFIED WITH mysql_native_password BY 'Root@123456';

GRANT REPLICATION SLAVE ON *.* TO 'nwq'@'%';


5.(主1)服务器执行一下命令
    
    CHANGE REPLICATION SOURCE TO
    SOURCE_HOST='10.0.1.155',
    SOURCE_USER='nwq',
    SOURCE_PASSWORD='Root@123456',
    SOURCE_LOG_FILE='mysql-bin.000002',
    SOURCE_LOG_POS=668;
    
    start slave;


6.测试是否可以登录(主1)
mysql -unwq -pRoot@123456 -h 10.0.1.155




7.测试--主主状态
主1:
show master status;
show slave status\G;

主2:
show master status;
show slave status\G;


具体状态
#主1:
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000002 |      157 |              | mysql            |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for source to send event
                  Master_Host: 10.0.1.155
                  Master_User: nwq
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 668
               Relay_Log_File: centos7mage-relay-bin.000002
                Relay_Log_Pos: 326
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes



#主2:
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000002 |      668 |              |                  |                   |
+------------------+-----

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for source to send event
                  Master_Host: 10.0.1.154
                  Master_User: nwq
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 157
               Relay_Log_File: centos7mage-relay-bin.000007
                Relay_Log_Pos: 326
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes




8.测试

#主2:创建nwq数据库--主1是否显示?
mysql> create database nwq;
Query OK, 1 row affected (0.00 sec)

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


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


#主1:创建nwq数据库--主2是否显示?
mysql> create database kaige;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| kaige              |
| mysql              |
| nwq                |
| performance_schema |
| sys                |
+--------------------+
6 rows in set (0.01 sec)


6.mysql主主+keepalived

#步骤
虚拟机:环境
主1:10.0.1.154
主2:10.0.1.155


tips:mysql主主配置已配置完成(这里就不配置了)



1.安装keepalived(主1主2)
yum -y install keepalived
 systemctl start keepalived.service 
 systemctl status keepalived.service



2.配置高可用(主1主2)
 vim /etc/keepalived/keepalived.conf

主1配置:
! Configuration File for keepalived
   
    global_defs {
        router_id lb01    #高可用集群标识 不能冲突
    }
   
    vrrp_instance it {       #家族名字
        state MASTER          #身份
        interface eth0        #网卡名称 这里要与你的网卡名要一样
        virtual_router_id 51    #身份信息 两台要一致
        priority 150           #优先级   数字越高 等级越大
        advert_int 1           #组播发送间隔时间
        authentication {       #人证过程
            auth_type PASS
            auth_pass 1111
        }
        virtual_ipaddress {
            10.0.1.100/24          #配置虚拟vip
        }
    }
    
    
  主2配置
  vim /etc/keepalived/keepalived.conf
  ! Configuration File for keepalived
   
    global_defs {
        router_id lb02    #高可用集群标识 不能冲突
    }
   
    vrrp_instance it {       #家族名字
        state MASTER          #身份
        interface eth0        #网卡名称 这里要与你的网卡名要一样
        virtual_router_id 51    #身份信息 两台要一致
        priority 100           #优先级   数字越高 等级越大
        advert_int 1           #组播发送间隔时间
        authentication {       #人证过程
            auth_type PASS
            auth_pass 1111
        }
        virtual_ipaddress {
            10.0.1.100/24          #配置虚拟vip
        }
    }


3.测试虚拟ip是否可以登录
   mysql -unwq -pRoot@123456 -h 10.0.1.100(测试虚拟ip是否可以登录)
   
   


4.测试高可用(是否有效)
   
 #当前状态:  
 主1
 [root@centos7mage ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:bb:fc:42 brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.154/24 brd 10.0.1.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet 10.0.1.100/24 scope global secondary eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::676d:5f34:8921:618c/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

 
 主2
  [root@centos7mage keepalived]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:89:15:ce brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.155/24 brd 10.0.1.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::ac4d:d8fe:8c9e:2688/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever



#模拟主1高可用断了??
主1:
  systemctl stop keepalived.service 
  
  
  
主2:
[root@centos7mage keepalived]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:89:15:ce brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.155/24 brd 10.0.1.255 scope global noprefixroute dynamic eth0
       valid_lft 1313sec preferred_lft 1313sec
    inet 10.0.1.100/24 scope global secondary eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::ac4d:d8fe:8c9e:2688/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever







shell脚本安装mysql5.6

1.
yum -y install gcc gcc-c++ cmake bison bison-devel zlib-devel libcurl-devel libarchive-devel boost-devel   ncurses-devel gnutls-devel libxml2-devel openssl-devel libevent-devel libaio-devel perl-Data-Dumper


2.
useradd -r -s /sbin/nologin -d /data/mysql mysql


3.
https://downloads.mysql.com/archives/community/


4.


tar xvf   mysql-5.6.51.tar.gz  -C /usr/local/src


5.
cd mysql-5.6.51/
cmake . \
-DCMAKE_INSTALL_PREFIX=/apps/mysql \
-DMYSQL_DATADIR=/data/mysql/ \
-DSYSCONFDIR=/etc/ \
-DMYSQL_USER=mysql \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DWITHOUT_MROONGA_STORAGE_ENGINE=1 \
-DWITH_DEBUG=0 \
-DWITH_READLINE=1 \
-DWITH_SSL=system \
-DWITH_ZLIB=system \
-DWITH_LIBWRAP=0 \
-DENABLED_LOCAL_INFILE=1 \
-DMYSQL_UNIX_ADDR=/data/mysql/mysql.sock \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci
make -j 8 && make install

7.MHA-高可用(vip)


#步骤
环境:虚拟机
主:10.0.1.154
从1:10.0.1.155
从2:10.0.1.156


一.安装数据库(编译-二进制)

1、创建用户
[root@mysqlmaster~]# groupadd mysql
[root@mysqlmaster~]# useradd -r -g mysql -s /usr/sbin/nologin mysql
2、创建目录
[root@mysqlmaster~]# mkdir /data/mysql -p
[root@mysqlmaster~]# chown -R mysql.mysql /data/mysql
3、准备二进制程序


[root@mysqlmaster~]# wget https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.32-linux-glibc2.12-x86_64.tar
或
wget https://cdn.mysql.com/archives/mysql-5.6/mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz


--2023-06-07 10:54:29--  https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.32-linux-glibc2.12-x86_64.tar
正在解析主机 cdn.mysql.com (cdn.mysql.com)... 104.70.237.54
正在连接 cdn.mysql.com (cdn.mysql.com)|104.70.237.54|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1005660160 (959M) [application/x-tar]
正在保存至: “mysql-8.0.32-linux-glibc2.12-x86_64.tar”

100%[====================================================================================================>] 1,005,660,160 26.6MB/s 用时 29s    

2023-06-07 10:54:58 (32.8 MB/s) - 已保存 “mysql-8.0.32-linux-glibc2.12-x86_64.tar” [1005660160/1005660160])

[root@mysqlmaster~]# tar xvf mysql-8.0.32-linux-glibc2.12-x86_64.tar
tar zxvf mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz

mysql-test-8.0.32-linux-glibc2.12-x86_64.tar.xz
mysql-8.0.32-linux-glibc2.12-x86_64.tar.xz
mysql-router-8.0.32-linux-glibc2.12-x86_64.tar.xz

[root@mysqlmaster~]#tar xf mysql-8.0.32-linux-glibc2.12-x86_64.tar.xz -C /usr/local/
[root@mysqlmaster~]# cd /usr/local
[root@node-centos7-70 local]# ln -sv mysql-8.0.32-linux-glibc2.12-x86_64 mysql
"mysql" -> "mysql-8.0.32-linux-glibc2.12-x86_64"


4、安装依赖包
[root@mysqlmaster~]# yum install -y libaio numactl-libs
5、设置PATH环境变量
[root@mysqlmaster~]# echo "PATH=/usr/local/mysql/bin:$PATH" > /etc/profile.d/mysql.sh
[root@mysqlmaster~]# . /etc/profile.d/mysql.sh
6、创建配置文件


[root@mysqlmaster~]# tee > /etc/my.cnf << EOF
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
pid-file=/data/mysql/mysql.pid
log-error=/data/mysql/mysql.log

[client]
socket=/data/mysql/mysql.sock
EOF


7、创建数据库文件,并提取root密码


[root@mysqlmaster~]# mysqld --initialize --user=mysql --datadir=/data/mysql
[root@mysqlmaster~]# grep password /data/mysql/mysql.log
2023-06-07T03:20:09.342795Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: ,*9LyAr6wrr#
[root@mysqlmaster~]# awk '/temporary password/{print $NF}' /data/mysql/mysql.log 
,*9LyAr6wrr#


8、创建服务脚本,并启动服务
[root@mysqlmaster~]# cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@mysqlmaster~]# chkconfig --add mysqld
[root@mysqlmaster~]# service mysqld start
Starting MySQL... SUCCESS! 
9、修改初始密码,测试访问数据库

mysql(master)
sJDiAp3,stla


mysql(slave)
Mi*tYko=d7ZJ


mysqladmin -uroot -p'ODq06w:4FwzO' password 'mysql'

mysqladmin -uroot -p'p?vfl2d_iE5l' password 'mysql'

[root@mysqlmaster~]# mysqladmin -uroot -p',*9LyAr6wrr#' password 'mysql'
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
[root@mysqlmaster~]# mysql -uroot -pmysql
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 9
Server version: 8.0.32 MySQL Community Server - GPL

Copyright (c) 2000, 2023, 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           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> 





9.重启安装(查看服务)
service mysqld start
service mysqld stop
ss-tulpn




二.主库配置

mysql -uroot -pmysql
mysql -uroot -pmysql
1.关闭防火墙
开放指定的3306端口号(生产环境当中建议开放指定端口)
firewall-cmd --zone=public --add-port=3306/tcp -permanent
firewall-cmd -reload

关闭服务器的防火墙
systemctl stop firewalld
systemctl disable firewalld

2.配置主库文件信息



vim /etc/my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
pid-file=/data/mysql/mysql.pid
log-error=/data/mysql/mysql.log




log-bin = mysql-bin  #开启binlog日志
server-id=1    #默认为1 不能一样
binlog_format=mixed    #设定MySQL二进制日志记录事务的方式,此处采用智能混合格式,根据事务特性自动选择最优方式。
expire_logs_days=10   #设置MySQL二进制日志文件在10天后自动清除,以释放存储空间。


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




#重启数据库
service mysql restart 



3.登录数据库-创建远程连接的账号--并授予主从复制权限(主库)
#登录mysql
mysql -uroot -pmysql
#创建nwq用户,并设置密码,该用户可在任意主机连接改mysql服务

grant all on *.* to nwq@"%" identified by "Hello123";
flush privileges;


#测试nwq用户是否可以在其他机器上登录
mysql -unwq -pHello123 -h 10.0.1.154



----------------------------------------------------------------
###tips:正常这里需要测试创建的这个用户,有没有存在,我们这里是需要创建mha高可用,这个用户在三台所有节点上都创建一下,并授予相关权限,我这里踩了很大的坑,一坑接一坑,
1.虚拟机克隆--uuid问题
2.主服务器nwq授权权限不够问题
3.在执行数据库权限等问题时,最好停止数据库,在进行设置,因为我们的每个操作,还是需要再数据库停止状态下执行才安全
4. 如果遇见账户密码不对,也可以删除账户,重新设置账户和密码DROP USER 'nwq'@'%';
5.最好执行每个命令都刷新一下flush privileges;



----------------------------------------------------------------

#查看二进制日志坐标
show master status;

mysql> show master status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000004 |      658 |              | mysql            |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)



4.从库配置(从库1/2)

vim /etc/my.cnf

从库1
log-bin = mysql-bin
server-id=2

从库2
log-bin = mysql-bin
server-id=3

#super-read-only (设置超级管理员页只读)--非必要

#重启数据库
service mysql restart 


5.登录数据库--设置从库配置
#登录mysql
mysql -uroot -pmysql

#mysql5.7以前版本
CHANGE MASTER TO
    MASTER_HOST='X',
    MASTER_USER='X',
    MASTER_PASSWORD='XI',
    MASTER_LOG_FILE='XY',
    MASTER_LOG_POS=X;
    
    #mysql8.0以上版本
    CHANGE REPLICATION SOURCE TO 
    SOURCE_HOST='X',         #主库ip地址
    SOURCE_USER='X',       #连接数据库的用户名
    SOURCE_PASSWORD='XI',   #连接主库的密码
    RELAY_LOG_FILE='XY', #--binlog日志文件名 注意:这里应该是RELAY_LOG_FILE而不是MASTER_LOG_FILE,因为后者是主库的设置项
    RELAY_LOG_POS=X; #--binlog日志文件位置 同样,应使用RELAY_LOG_POS来指定中继日志的位置
    
 
 
 #执行这段(旧版本命令(mysql5.7)从库1
 CHANGE MASTER TO
    MASTER_HOST='10.0.1.154',
    MASTER_USER='nwq',
    MASTER_PASSWORD='Hello123',
    MASTER_LOG_FILE='mysql-bin.000001',
    MASTER_LOG_POS=154;
    
    
    #从库2
    CHANGE MASTER TO
    MASTER_HOST='10.0.1.154',
    MASTER_USER='nwq',
    MASTER_PASSWORD='Hello123',
    MASTER_LOG_FILE='mysql-bin.000001',
    MASTER_LOG_POS=585;
    
   
  # tips:当配置第二个或多个从的时候,一定要再重新获取主的binlog文件名和binlog文件位置或者一下重新配置一主二从也可以
 

 
  
  
   
   
6.启动复制进程(从库1/2)
start slave;






故障问题--uuid问题
原因:虚拟机克隆原因
解决:
stop slave; 
select uuid();

vim /data/mysql/auto.cnf
[auto]
server-uuid=919ffd5e-fa24-11ee-854a-000c2924ffe2 # 按照这个16进制格式,修改server-uuid,重启mysql即可


8f3a1727-fa24-11ee-9f13-000c298915ce
919ffd5e-fa24-11ee-854a-000c2924ffe2 






7.查看从库是否成功与主库同步状态
#show slave status\G;

#从库1状态
mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.1.154
                  Master_User: nwq
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 585
               Relay_Log_File: centos7mage-relay-bin.000003
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes




#从库2状态
mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.1.154
                  Master_User: nwq
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 585
               Relay_Log_File: centos7mage-relay-bin.000003
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes





8.测试
#主库数据库

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

#从库数据库
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)
    
    
#创建数据库(主库)---看从库是否有
主库(创建数据库)
mysql> create database kaige;
Query OK, 1 row affected (0.00 sec)

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



从库1:
Query OK, 0 rows affected, 1 warning (0.00 sec)

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


从库2:
mysql> start slave;
Query OK, 0 rows affected, 1 warning (0.00 sec)

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









-------------------------------------------------------------
                           MHA高可用架构
#步骤

环境:虚拟机
主库:10.0.1.154    (master)
从库1:10.0.1.155    (slave)
从库2:10.0.1.156     (MHA manager)






1.配置关键程序软连接(三个都要做)
ln -s /data/mysql/bin/mysqlbinlog    /usr/bin/mysqlbinlog
ln -s /data/mysql/bin/mysql          /usr/bin/mysql

2.配置互信(三个都要做)

ssh-keygen
cd .ssh/
cp id_rsa.pub authorized_keys
scp -r /root/.ssh/ @10.0.1.155:/root
scp -r /root/.ssh/ @10.0.1.156:/root
#测试
 ssh 10.0.1.155 ip a
 ssh 10.0.1.156 ip a
 ssh 10.0.1.154 ip a (在另外一台上测试就可)


3.安装node(三个节点都要做)

#安装依赖
yum install perl-DBD-MySQL  perl-Config-Tiny perl-Log-Dispatch perl-Parallel-ForkManager -y

#下载noderpm包
https://files.cnblogs.com/files/blogs/816085/mha4mysql-node-0.56.tar.gz?t=1712975272&download=true

wget https://github.com/yoshinorim/mha4mysql-node/releases/download/v0.58/mha4mysql-node-0.58-0.el7.centos.noarch.rpm

rpm -ivh mha4mysql-node-0.56-0.el6.noarch.rpm 





4.安装manager软件(从库2)
 yum install -y perl-DBD-MySQL perl-Config-Tiny perl-Log-Dispatch perl-Parallel-ForkManager perl-Config-IniFiles perl-Time-HiRes -y
 
wget https://github.com/yoshinorim/mha4mysql-manager/releases/download/v0.58/mha4mysql-manager-0.58-0.el7.centos.noarch.rpm
 

5.创建MHA专用监控管理用户(主库从库1从库2都要建立授权这个账户)
----------------------------------------------------------------
#如果是MySQL8.0执行下面操操作
mysql> create user repluser@'10.0.0.%' identified by 'magedu';
mysql> grant replication slave on *.* to repluser@'10.0.0.%';
mysql> create user mhauser@'10.0.0.%' identified by 'magedu';
mysql> grant all on *.* to mhauser@'10.0.0.%';


-----------------------------------------------------------
#如果是MySQL8.0以前版本执行下面操操作
mysql>grant replication slave on *.* to repluser@'10.0.0.%' identified by 
'magedu';
mysql>grant all on *.* to mhauser@'10.0.0.%' identified by 'magedu';

#检查所有从库是否同步mha账户

select user, host from mysql.user;


#我自己创建mha的命令(根据自己的版本设置)
mysql> create user mha@'%' identified by 'mha';
Query OK, 0 rows affected (0.00 sec)

mysql> grant all on *.* to mha@'%';
Query OK, 0 rows affected (0.00 sec



从库1
mysql> select user, host from mysql.user;
+---------------+-----------+
| user          | host      |
+---------------+-----------+
| mha           | %         |
| mha           | 10.0.0.%  |
| mysql.session | localhost |
| mysql.sys     | localhost |
| root          | localhost |
+---------------+-----------+
5 rows in set (0.00 sec)



从库2
mysql> select user, host from mysql.user;
+---------------+-----------+
| user          | host      |
+---------------+-----------+
| mha           | %         |
| mha           | 10.0.0.%  |
| mysql.session | localhost |
| mysql.sys     | localhost |
| root          | localhost |
+---------------+-----------+
5 rows in set (0.00 sec)


-------------------------------------------------------------
以防万一,最好把之前的主从账号也执行一下,在三台机器上或者在主库机器上,
grant all on *.* to nwq@"%" identified by "Hello123";
flush privileges;


----------------------------------------------------------


主库1状态
mysql> select user, host from mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mha              | %         |
| nwq              | %         |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
6 rows in set (0.00 sec)

从库1状态
mysql> select user,host from mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mha              | %         |
| nwq              | %         |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
6 rows in set (0.01 sec)




从库2状态
mysql> select user, host from mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mha              | %         |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
5 rows in set (0.00 sec)




6.创建配置文件目录(从库2)



mkdir -p /etc/mha
创建日志目录
mkdir -p /var/log/mha/app1
编辑配置文件
cat > /etc/mha/app1.cnf <<EOF
[server default]
manager_log=/var/log/mha/app1/manager.log        
manager_workdir=/var/log/mha/app1            
master_binlog_dir=/data/mysql
remote_workdir=/data/mha/app1/
ssh_user=root 
user=mha                                  
password=mha                       
ping_interval=2
repl_password=Hello123
repl_user=nwq
ssh_user=root
master_ip_failover_script=/usr/local/bin/master_ip_failover
report_script=/usr/local/bin/sendmail.sh
check_repl_delay=0
[server1]                                   
hostname=10.0.1.154
candidate_master=1
port=3306                                 
[server2]            
hostname=10.0.1.155
candidate_master=1
port=3306
[server3]
hostname=10.0.1.156
port=3306
EOF




7.配置虚拟vip脚本(主库)
cd /usr/local/bin
vim master_ip_failover


#!/usr/bin/env perl

#  Copyright (C) 2011 DeNA Co.,Ltd.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#  Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

## Note: This is a sample script and is not complete. Modify the script based on your environment.

use strict;
use warnings FATAL => 'all';

use Getopt::Long;
use MHA::DBHelper;

my (
  $command,        $ssh_user,         $orig_master_host,
  $orig_master_ip, $orig_master_port, $new_master_host,
  $new_master_ip,  $new_master_port,  $new_master_user,
  $new_master_password
);
my $vip = '10.0.1.100/24';
my $key = "1";
my $ssh_start_vip = "/sbin/ifconfig eth0:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig eth0:$key down";

GetOptions(
  'command=s'             => \$command,
  'ssh_user=s'            => \$ssh_user,
  'orig_master_host=s'    => \$orig_master_host,
  'orig_master_ip=s'      => \$orig_master_ip,
  'orig_master_port=i'    => \$orig_master_port,
  'new_master_host=s'     => \$new_master_host,
  'new_master_ip=s'       => \$new_master_ip,
  'new_master_port=i'     => \$new_master_port,
  'new_master_user=s'     => \$new_master_user,
  'new_master_password=s' => \$new_master_password,
);

exit &main();

sub main {
  if ( $command eq "stop" || $command eq "stopssh" ) {

    # $orig_master_host, $orig_master_ip, $orig_master_port are passed.
    # If you manage master ip address at global catalog database,
    # invalidate orig_master_ip here.
    my $exit_code = 1;
    eval {

      # updating global catalog, etc
      $exit_code = 0;
    };
    if ($@) {
      warn "Got Error: $@\n";
      exit $exit_code;
    }
    exit $exit_code;
  }
    elsif ( $command eq "start" ) {

        # all arguments are passed.
        # If you manage master ip address at global catalog database,
        # activate new_master_ip here.
        # You can also grant write access (create user, set read_only=0, etc) here.
        my $exit_code = 10;
        eval {
            print "Enabling the VIP - $vip on the new master - $new_master_host \n";
            &start_vip();
            &stop_vip();
            $exit_code = 0;
        };
        if ($@) {
            warn $@;
            exit $exit_code;
        }
        exit $exit_code;
    }
    elsif ( $command eq "status" ) {
        print "Checking the Status of the script.. OK \n";
        `ssh $ssh_user\@$orig_master_host \" $ssh_start_vip \"`;
        exit 0;
    }
    else {
        &usage();
        exit 1;
    }
}


sub start_vip() {
    `ssh $ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old_master 
sub stop_vip() {
   `ssh $ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
}


sub usage {
  print
"Usage: master_ip_failover --command=start|stop|stopssh|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --new_master_host=host --new_master_ip=ip --new_master_port=port\n";
}

#给予执行权限
chmod +x master_ip_failover


#配置虚拟vip(主库)
yum -y install net-tools


ip a a 10.0.1.100/24 dev eth0(#我们这里的脚本是老式命令,所以这个不能用,或者你可以改一下脚本)
ifconfig eth0:1 10.0.1.100/24(临时添加)

ifconfig





8.报警脚本(主库)
cd /usr/local/bin/
vim sendmail.sh

#!/bin/bash
#
#********************************************************************
#Author:		nwq
#QQ: 			3078499367
#Date: 			2024-06-17
#FileName:		/usr/local/bin/sendmail.sh
#URL: 			http://www.sansi.fun
#Description:		The test script
#Copyright (C): 	2024 All rights reserved
#********************************************************************
echo "MHA is failover" |mail -s "MHA异常警告" 15178374440@163.com




---------------------------------------------------------------
#没有配置邮箱的这里可以再配置一下
安装postfix       yum -y install postfix
安装mailx          yum -y install mailx 
systemctl enable postfix
vim /etc/mail.rc

set from=15178374440@163.com
set smtp=smtp.163.com
set smtp-auth-user=15178374440@163.com
set smtp-auth-password=EEIRWSHHDUOTZZZV
set smtp-auth=login
----------------------------------------------------------------






9.添加主库(master)my.cnf配置
vim /etc/my.cnf

skip_name_resolve=1
general_log

service mysqld restart

10.添加从库1/2(slave)my.cnf配置
从库1:
vim /etc/my.cnf

read_only
relay_log_purge=0
skip_name_resolve=1    #禁止反向解析
general_log

service mysqld restart


从库2:
vim /etc/my.cnf

read_only
relay_log_purge=0
skip_name_resolve=1    #禁止反向解析
general_log

service mysqld restart
------------------------------------------------------------
#tips:msyql处理主从不一致问题流程
1.停掉数据库状态-----stop slave;
2.重新设置从库信息-------reset slave all;
3.重新配置master信息----CHANGE MASTER TO
  MASTER_HOST='10.0.1.154',
  MASTER_USER='nwq',
  MASTER_PASSWORD='Hello123',
  MASTER_PORT=3306,
  MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=22454520;
4.启用数据库状态--------start slave;
--------------------------------------------------------------





11.测试是否主从状态是否正常
主库
CREATE DATABASE IF NOT EXISTS hellodb;
USE hellodb;
CREATE TABLE IF NOT EXISTS teachers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    age INT,
    gender ENUM('M', 'F') -- 或者使用 VARCHAR 类型存储性别
);
INSERT INTO teachers (name, age, gender) VALUES ('y', 32, 'M');

从库1:
select * from hellodb.teachers;


从库2:
select * from hellodb.teachers;



---------------------------------------------------------------
具体从库1 2 状态
mysql> select * from hellodb.teachers;
+----+------+------+--------+
| id | name | age  | gender |
+----+------+------+--------+
|  1 | y    |   32 | M      |
+----+------+------+--------+
1 row in set (0.00 sec)

mysql> select * from hellodb.teachers;
+----+------+------+--------+
| id | name | age  | gender |
+----+------+------+--------+
|  1 | y    |   32 | M      |
+----+------+------+--------+
1 row in set (0.00 sec)
----------------------------------------------------------------












12.验证SSH状态检查(从2)
masterha_check_ssh  --conf=/etc/mha/app1.cnf




具体状态
[root@centos7mage ~]# masterha_check_ssh  --conf=/etc/mha/app1.cnf
Sun Apr 14 10:28:50 2024 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Sun Apr 14 10:28:50 2024 - [info] Reading application default configuration from /etc/mha/app1.cnf..
Sun Apr 14 10:28:50 2024 - [info] Reading server configuration from /etc/mha/app1.cnf..
Sun Apr 14 10:28:50 2024 - [info] Starting SSH connection tests..
Sun Apr 14 10:28:51 2024 - [debug] 
Sun Apr 14 10:28:50 2024 - [debug]  Connecting via SSH from root@10.0.1.154(10.0.1.154:22) to root@10.0.1.155(10.0.1.155:22)..
Sun Apr 14 10:28:50 2024 - [debug]   ok.
Sun Apr 14 10:28:50 2024 - [debug]  Connecting via SSH from root@10.0.1.154(10.0.1.154:22) to root@10.0.1.156(10.0.1.156:22)..
Sun Apr 14 10:28:51 2024 - [debug]   ok.
Sun Apr 14 10:28:51 2024 - [debug] 
Sun Apr 14 10:28:51 2024 - [debug]  Connecting via SSH from root@10.0.1.155(10.0.1.155:22) to root@10.0.1.154(10.0.1.154:22)..
Sun Apr 14 10:28:51 2024 - [debug]   ok.
Sun Apr 14 10:28:51 2024 - [debug]  Connecting via SSH from root@10.0.1.155(10.0.1.155:22) to root@10.0.1.156(10.0.1.156:22)..
Sun Apr 14 10:28:51 2024 - [debug]   ok.
Sun Apr 14 10:28:52 2024 - [debug] 
Sun Apr 14 10:28:51 2024 - [debug]  Connecting via SSH from root@10.0.1.156(10.0.1.156:22) to root@10.0.1.154(10.0.1.154:22)..
Sun Apr 14 10:28:51 2024 - [debug]   ok.
Sun Apr 14 10:28:51 2024 - [debug]  Connecting via SSH from root@10.0.1.156(10.0.1.156:22) to root@10.0.1.155(10.0.1.155:22)..
Sun Apr 14 10:28:52 2024 - [debug]   ok.
Sun Apr 14 10:28:52 2024 - [info] All SSH connection tests passed successfully.



13.验证主从复制状态
masterha_check_repl  --conf=/etc/mha/app1.cnf




具体效果展示
[root@centos7mage ~]# masterha_check_repl  --conf=/etc/mha/app1.cnf

---------------------------------------------------------------
                         故障问题实例-解决
---------------------------------------------------------------
Sun Apr 14 22:45:14 2024 - [error][/usr/share/perl5/vendor_perl/MHA/Server.pm, ln398] 10.0.1.155(10.0.1.155:3306): User nwq does not exist or does not have REPLICATION SLAVE privilege! Other slaves can not start replication from this host.
Sun Apr 14 22:45:14 2024 - [error][/usr/share/perl5/vendor_perl/MHA/MasterMonitor.pm, ln427] Error happened on checking configurations.  at /usr/share/perl5/vendor_perl/MHA/ServerManager.pm line 1403.
Sun Apr 14 22:45:14 2024 - [error][/usr/share/perl5/vendor_perl/MHA/MasterMonitor.pm, ln525] Error happened on monitoring servers.
Sun Apr 14 22:45:14 2024 - [info] Got exit code 1 (Not master dead).

MySQL Replication Health is NOT OK!


问题:从库1 从库2 那边没有mysql主从的账户,nwq不在从库1 从库2上,因此无法连接

解决:
msyql -uroot -pmysql

select user, host from mysql.user;
mysql> select user, host from mysql.user;
+---------------+-----------+
| user          | host      |
+---------------+-----------+
| mha           | %         |
| mysql.session | localhost |
| mysql.sys     | localhost |
| root          | localhost |
+---------------+-----------+

 stop slave;
 GRANT REPLICATION SLAVE ON *.* TO 'nwq'@'%' IDENTIFIED BY 'Hello123';
FLUSH PRIVILEGES;
start slave;
show slave status\G;
另一台也是如此配置
----------------------------------------------------------------

Sun Apr 14 22:58:00 2024 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Sun Apr 14 22:58:00 2024 - [info] Reading application default configuration from /etc/mha/app1.cnf..
Sun Apr 14 22:58:00 2024 - [info] Reading server configuration from /etc/mha/app1.cnf..
Sun Apr 14 22:58:00 2024 - [info] MHA::MasterMonitor version 0.58.
Sun Apr 14 22:58:01 2024 - [info] GTID failover mode = 0
Sun Apr 14 22:58:01 2024 - [info] Dead Servers:
Sun Apr 14 22:58:01 2024 - [info] Alive Servers:
Sun Apr 14 22:58:01 2024 - [info]   10.0.1.154(10.0.1.154:3306)
Sun Apr 14 22:58:01 2024 - [info]   10.0.1.155(10.0.1.155:3306)
Sun Apr 14 22:58:01 2024 - [info]   10.0.1.156(10.0.1.156:3306)
Sun Apr 14 22:58:01 2024 - [info] Alive Slaves:
Sun Apr 14 22:58:01 2024 - [info]   10.0.1.155(10.0.1.155:3306)  Version=5.7.29-log (oldest major version between slaves) log-bin:enabled
Sun Apr 14 22:58:01 2024 - [info]     Replicating from 10.0.1.154(10.0.1.154:3306)
Sun Apr 14 22:58:01 2024 - [info]     Primary candidate for the new Master (candidate_master is set)
Sun Apr 14 22:58:01 2024 - [info]   10.0.1.156(10.0.1.156:3306)  Version=5.7.29-log (oldest major version between slaves) log-bin:enabled
Sun Apr 14 22:58:01 2024 - [info]     Replicating from 10.0.1.154(10.0.1.154:3306)
Sun Apr 14 22:58:01 2024 - [info] Current Alive Master: 10.0.1.154(10.0.1.154:3306)
Sun Apr 14 22:58:01 2024 - [info] Checking slave configurations..
Sun Apr 14 22:58:01 2024 - [info] Checking replication filtering settings..
Sun Apr 14 22:58:01 2024 - [info]  binlog_do_db= , binlog_ignore_db= 
Sun Apr 14 22:58:01 2024 - [info]  Replication filtering check ok.
Sun Apr 14 22:58:01 2024 - [info] GTID (with auto-pos) is not supported
Sun Apr 14 22:58:01 2024 - [info] Starting SSH connection tests..
Sun Apr 14 22:58:22 2024 - [info] All SSH connection tests passed successfully.
Sun Apr 14 22:58:22 2024 - [info] Checking MHA Node version..
Sun Apr 14 22:58:22 2024 - [info]  Version check ok.
Sun Apr 14 22:58:22 2024 - [info] Checking SSH publickey authentication settings on the current master..
Sun Apr 14 22:58:22 2024 - [info] HealthCheck: SSH to 10.0.1.154 is reachable.
Sun Apr 14 22:58:22 2024 - [info] Master MHA Node version is 0.58.
Sun Apr 14 22:58:22 2024 - [info] Checking recovery script configurations on 10.0.1.154(10.0.1.154:3306)..
Sun Apr 14 22:58:22 2024 - [info]   Executing command: save_binary_logs --command=test --start_pos=4 --binlog_dir=/data/mysql --output_file=/data/mha/app1//save_binary_logs_test --manager_version=0.58 --start_file=mysql-bin.000005 
Sun Apr 14 22:58:22 2024 - [info]   Connecting to root@10.0.1.154(10.0.1.154:22).. 
  Creating /data/mha/app1 if not exists..    ok.
  Checking output directory is accessible or not..
   ok.
  Binlog found at /data/mysql, up to mysql-bin.000005
Sun Apr 14 22:58:22 2024 - [info] Binlog setting check done.
Sun Apr 14 22:58:22 2024 - [info] Checking SSH publickey authentication and checking recovery script configurations on all alive slave servers..
Sun Apr 14 22:58:22 2024 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user='mha' --slave_host=10.0.1.155 --slave_ip=10.0.1.155 --slave_port=3306 --workdir=/data/mha/app1/ --target_version=5.7.29-log --manager_version=0.58 --relay_log_info=/data/mysql/relay-log.info  --relay_dir=/data/mysql/  --slave_pass=xxx
Sun Apr 14 22:58:22 2024 - [info]   Connecting to root@10.0.1.155(10.0.1.155:22).. 
  Checking slave recovery environment settings..
    Opening /data/mysql/relay-log.info ... ok.
    Relay log found at /data/mysql, up to centos7mage-relay-bin.000018
    Temporary relay log file is /data/mysql/centos7mage-relay-bin.000018
    Checking if super_read_only is defined and turned on.. not present or turned off, ignoring.
    Testing mysql connection and privileges..
mysql: [Warning] Using a password on the command line interface can be insecure.
 done.
    Testing mysqlbinlog output.. done.
    Cleaning up test file(s).. done.
Sun Apr 14 22:58:23 2024 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user='mha' --slave_host=10.0.1.156 --slave_ip=10.0.1.156 --slave_port=3306 --workdir=/data/mha/app1/ --target_version=5.7.29-log --manager_version=0.58 --relay_log_info=/data/mysql/relay-log.info  --relay_dir=/data/mysql/  --slave_pass=xxx
Sun Apr 14 22:58:23 2024 - [info]   Connecting to root@10.0.1.156(10.0.1.156:22).. 
  Checking slave recovery environment settings..
    Opening /data/mysql/relay-log.info ... ok.
    Relay log found at /data/mysql, up to centos7mage-relay-bin.000018
    Temporary relay log file is /data/mysql/centos7mage-relay-bin.000018
    Checking if super_read_only is defined and turned on.. not present or turned off, ignoring.
    Testing mysql connection and privileges..
mysql: [Warning] Using a password on the command line interface can be insecure.
 done.
    Testing mysqlbinlog output.. done.
    Cleaning up test file(s).. done.
Sun Apr 14 22:58:23 2024 - [info] Slaves settings check done.
Sun Apr 14 22:58:23 2024 - [info] 
10.0.1.154(10.0.1.154:3306) (current master)
 +--10.0.1.155(10.0.1.155:3306)
 +--10.0.1.156(10.0.1.156:3306)

Sun Apr 14 22:58:23 2024 - [info] Checking replication health on 10.0.1.155..
Sun Apr 14 22:58:23 2024 - [info]  ok.
Sun Apr 14 22:58:23 2024 - [info] Checking replication health on 10.0.1.156..
Sun Apr 14 22:58:23 2024 - [info]  ok.
Sun Apr 14 22:58:23 2024 - [info] Checking master_ip_failover_script status:
Sun Apr 14 22:58:23 2024 - [info]   /usr/local/bin/master_ip_failover --command=status --ssh_user=root --orig_master_host=10.0.1.154 --orig_master_ip=10.0.1.154 --orig_master_port=3306 
Checking the Status of the script.. OK 
Sun Apr 14 22:58:23 2024 - [info]  OK.
Sun Apr 14 22:58:23 2024 - [warning] shutdown_script is not defined.
Sun Apr 14 22:58:23 2024 - [info] Got exit code 0 (Not master dead).

MySQL Replication Health is OK.






14.开启MHA(从2)

nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover  < /dev/null> /var/log/mha/app1/manager.log 2>&1 &


具体状态
[root@centos7mage ~]# nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover  < /dev/null> /var/log/mha/app1/manager.log 2>&1 &
[1] 12450
[root@centos7mage ~]# ps aux |grep mha
root      12450  0.8  2.2 299648 21980 pts/0    S    10:31   0:00 perl /usr/bin/masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover
root      12556  0.0  0.0 112812   980 pts/0    R+   10:32   0:00 grep --color=auto mha





15.启动MHA

#启动mha,默认是前台执行,生产环境一般是后台执行
nohup masterha_manager --conf=/etc/mha/app1.cnf --remove_dead_master_conf --ignore_last_failover  < /dev/null> /var/log/mha/app1/manager.log 2>&1 &


#测试环境:看状态可执行下面这条命令
masterha_manager --conf=/etc/mha/app1.cnf --
remove_dead_master_conf --ignore_last_failover


#如果想停止mha,可执行下面命令
master_stop --conf=/etc/mha/app1.cnf

#查看状态
masterha_check_status --conf=/etc/mha/app1.cnf

#查看mha工作状态日志(要mha启动才可以有,不启动没有的)
tail -f /var/log/mha/app1/manager.log 






16.测试
需求:因不可抗力原因,主库数据库掉线,
目的:实现从库2自动认主从库1为主节点,并且vip10.0.1.100切换到从库1上


模拟主库1断掉
service mysqld stop

从库2状态:
mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.1.155
                  Master_User: nwq
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000006
          Read_Master_Log_Pos: 154
               Relay_Log_File: centos7mage-relay-bin.000003
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql-bin.000006
             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: 154
              Relay_Log_Space: 912
              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: 11
                  Master_UUID: 919ffd5e-fa24-11ee-854a-000c2924ffe2
             Master_Info_File: /data/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)



从库1状态:

[root@centos7mage ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:89:15:ce brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.155/24 brd 10.0.1.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet 10.0.1.100/24 brd 10.0.1.255 scope global secondary eth0:1
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe89:15ce/64 scope link 
       valid_lft forever preferred_lft forever









----------------------------------------------------------------
主库my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
pid-file=/data/mysql/mysql.pid
log-error=/data/mysql/mysql.log



log-bin = mysql-bin  #开启binlog日志
server-id=1    #默认为1 不能一样
skip_name_resolve=1
general_log
#read-only=0    #1代表只读,0代表读写
#binlog-ignore-db=mysql   #忽略的数据库 指不需要同步的数据库
binlog_format=mixed    #设定MySQL二进制日志记录事务的方式,此处采用智能混合格式,根据事务特性自动选择最优方
式。
expire_logs_days=10   #设置MySQL二进制日志文件在10天后自动清除,以释放存储空间。



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


从库1:my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
pid-file=/data/mysql/mysql.pid
log-error=/data/mysql/mysql.log


log-bin = mysql-bin
server-id=11
read_only
relay_log_purge=0
skip_name_resolve=1
general_log

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





从库2:my.cnf
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock
pid-file=/data/mysql/mysql.pid
log-error=/data/mysql/mysql.log



log-bin = mysql-bin
server-id=13
read_only
relay_log_purge=0
skip_name_resolve=1
general_log

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




从库2:master_ip_failover

#!/usr/bin/env perl

#  Copyright (C) 2011 DeNA Co.,Ltd.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#  Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

## Note: This is a sample script and is not complete. Modify the script based on your environment.

use strict;
use warnings FATAL => 'all';

use Getopt::Long;
use MHA::DBHelper;

my (
  $command,        $ssh_user,         $orig_master_host,
  $orig_master_ip, $orig_master_port, $new_master_host,
  $new_master_ip,  $new_master_port,  $new_master_user,
  $new_master_password
);
my $vip = '10.0.1.100/24';
my $key = "1";
my $ssh_start_vip = "/sbin/ifconfig eth0:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig eth0:$key down";

GetOptions(
  'command=s'             => \$command,
  'ssh_user=s'            => \$ssh_user,
  'orig_master_host=s'    => \$orig_master_host,
  'orig_master_ip=s'      => \$orig_master_ip,
  'orig_master_port=i'    => \$orig_master_port,
  'new_master_host=s'     => \$new_master_host,
  'new_master_ip=s'       => \$new_master_ip,
  'new_master_port=i'     => \$new_master_port,
  'new_master_user=s'     => \$new_master_user,
  'new_master_password=s' => \$new_master_password,
);

exit &main();

sub main {
  if ( $command eq "stop" || $command eq "stopssh" ) {

    # $orig_master_host, $orig_master_ip, $orig_master_port are passed.
    # If you manage master ip address at global catalog database,
    # invalidate orig_master_ip here.
    my $exit_code = 1;
    eval {

      # updating global catalog, etc
      $exit_code = 0;
    };
    if ($@) {
      warn "Got Error: $@\n";
      exit $exit_code;
    }
    exit $exit_code;
  }
    elsif ( $command eq "start" ) {

        # all arguments are passed.
        # If you manage master ip address at global catalog database,
        # activate new_master_ip here.
        # You can also grant write access (create user, set read_only=0, etc) here.
        my $exit_code = 10;
        eval {
            print "Enabling the VIP - $vip on the new master - $new_master_host \n";
            &start_vip();
            &stop_vip();
            $exit_code = 0;
        };
        if ($@) {
            warn $@;
            exit $exit_code;
        }
        exit $exit_code;
    }
    elsif ( $command eq "status" ) {
        print "Checking the Status of the script.. OK \n";
        `ssh $ssh_user\@$orig_master_host \" $ssh_start_vip \"`;
        exit 0;
    }
    else {
        &usage();
        exit 1;
    }
}


sub start_vip() {
    `ssh $ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old_master 
sub stop_vip() {
   `ssh $ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
}


sub usage {
  print
"Usage: master_ip_failover --command=start|stop|stopssh|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --new_master_host=host --new_master_ip=ip --new_master_port=port\n";
}









从库2:sendmail.sh
#!/bin/bash
#
#********************************************************************
#Author:		nwq
#QQ: 			3078499367
#Date: 			2024-06-17
#FileName:		/usr/local/bin/sendmail.sh
#URL: 			http://www.sansi.fun
#Description:		The test script
#Copyright (C): 	2024 All rights reserved
#********************************************************************
echo "MHA is failover" |mail -s "MHA异常警告" 15178374440@163.com




从库2:app1.cnf
[server default]
manager_log=/var/log/mha/app1/manager.log        
manager_workdir=/var/log/mha/app1            
master_binlog_dir=/data/mysql
remote_workdir=/data/mha/app1/
ssh_user=root 
user=mha                                  
password=mha                       
ping_interval=2
repl_password=Hello123
repl_user=nwq
ssh_user=root
master_ip_failover_script=/usr/local/bin/master_ip_failover
report_script=/usr/local/bin/sendmail.sh
check_repl_delay=0
[server1]                                   
hostname=10.0.1.154
candidate_master=1
port=3306                                 
[server2]            
hostname=10.0.1.155
candidate_master=1
port=3306
[server3]
hostname=10.0.1.156
port=3306
EOF






----------------------------------------------------------------









8.生产环境mycat--读写分离


MyCat简介

MyCat是一个开源的分布式数据库中间件,主要用于解决大规模数据存储和处理的问题。它可以将多个MySQL数据库实例组成一个分布式数据库集群,实现读写分离、分库分表等功能,从而提升整个系统的性能和扩展性。

概念
- MyCat扮演着数据库代理的角色,应用程序不再直接连接MySQL服务器,而是通过MyCat进行交互。MyCat负责管理和调度后端MySQL数据库资源,隐藏了复杂的数据库分布和负载均衡策略。

特点
1. **水平扩展**:通过分片技术(sharding),MyCat可以将大量数据分布到多个MySQL服务器上,实现数据的水平扩展。
2. **读写分离**:支持主从复制,自动将读请求路由到从库,减轻主库的压力,提高并发读取性能。
3. **高可用**:能够在主库故障时自动切换到备库,保持业务连续性。
4. **SQL支持**:支持丰富的SQL查询和事务处理,兼容MySQL的大部分功能,提供统一的数据视图。

缺点
1. **复杂度增加**:引入MyCat后,数据库架构更为复杂,运维和管理成本提高,对于小规模应用场景可能得不偿失。
2. **定制化限制**:虽然MyCat支持很多MySQL的功能,但并不能保证完全兼容MySQL的所有特性,尤其是较新的特性或高级SQL功能可能存在不足。
3. **额外延迟**:由于MyCat作为中间层,会引入一定网络传输和处理时间,对于低延迟要求极高的场景可能会受到影响。

应用场景
- **大数据量**:当单个MySQL实例无法满足数据存储需求时,可以通过MyCat进行分库分表,实现海量数据存储和高效查询。
- **高并发读写**:在网站、电商、社交应用等高并发场景下,利用MyCat实现读写分离和负载均衡,提高系统吞吐量。
- **高可用要求**:对数据可用性和灾备有较高要求的业务场景,可通过MyCat实现多主多从、故障转移等机制,保障业务稳定运行。




#步骤
环境:虚拟机
10.0.1.164 mycat服务器
10.0.1.165 master(写)
10.0.1.166 slave(读)

或者
10.0.1.164 mycat+master(写)
10.0.1.165 slave1(读)
10.0.1.166 slave2(读)


----------------------------------------------------------------
             前期准备---配置一主一从或一主二从或一主多从
----------------------------------------------------------------
1 修改master和slave上的配置文件
#master上的my.cnf
[root@centos7~]#vim /etc/my.cnf
[mysqld]
server-id = 1
log-bin
#slave上的my.cnf
[mysqld]
server-id = 2
[root@centos7~]#service mysqld restart



2 Master上创建复制用户
[root@centos7~]#mysql -uroot -pmysql
MariaDB [(none)]>GRANT REPLICATION SLAVE ON *.* TO 'nwq'@'10.0.0.%' 
IDENTIFIED BY 'Hello123';
mysql> FLUSH PRIVILEGES;    
mysql> show master status;
+------------------+----------+--------------+------------------+----------------
---+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
Executed_Gtid_Set |
+------------------+----------+--------------+------------------+----------------
---+
|mariadb-bin.000001|      403 |              |                  |               
    |
+------------------+----------+--------------+------------------+----------------
---+
1 row in set (0.00 sec)



3 Slave上执行
[root@centos7~]#mysql -uroot -pmysql
mysql> CHANGE MASTER TO
->     MASTER_HOST='10.0.0.%',
->     MASTER_USER='nwq',
->     MASTER_PASSWORD='Hello123',
->     MASTER_LOG_FILE='mysql-bin.000001',
->     MASTER_LOG_POS=403;
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: 10.0.0.18
                 Master_User: repluser
                 Master_Port: 3306
               Connect_Retry: 60
             Master_Log_File: mariadb-bin.000001
         Read_Master_Log_Pos: 439
               Relay_Log_File: mariadb-relay-bin.000002
               Relay_Log_Pos: 689
       Relay_Master_Log_File: mariadb-bin.000001
             Slave_IO_Running: Yes
           Slave_SQL_Running: Yes
...省略..,

----------------------------------------------------------------

官方文档:https://www.yuque.com/ccazhw/ml3nkf/fbcdeaad5384da0ab43a326251fb18ae



1关闭防火墙
systemctl stop firewalld
setenforce 0
时间同步


2.安装jdk
yum install java-1.8.0-openjdk* -y
#如果yum源有的话,也可以用yum安装
JDK8: 链接: https://pan.baidu.com/s/1sQhSR5GgmxB3STpihOqCAw 提取码: 0b6l
链接: https://pan.baidu.com/s/1vVXfDwyaI8-P12-eYrzP4w?pwd=1122 提取码: 1122 


3.上传或下载mycat


链接: https://pan.baidu.com/s/1NoVIjHV9ivPm6tzZqckbdw?pwd=1122 提取码: 1122 


4.解压启动mycat

#解压到指定目录(或者随意)
mkdir -p /apps 
tar zxvf Mycat-server-1.6.7.4-release-20200105164103-linux.tar.gz 

#配置环境变量
echo 'PATH=/apps/mycat/bin:$PATH' > /etc/profile.d/mycat.sh
source /etc/profile.d/mycat.sh

#启动mycat
mycat stop  停止
mycat start  启动
mycat restart  重启


#启动日志状态
cd /apps/mycat/logs
tail -f wrapper.log

#代表启动成功
tips:INFO   | jvm 1    | 2024/04/15 18:55:38 | MyCAT Server startup successfully. see logs in logs/mycat.log



#查看端口号
ss -tulpn
netstat -tulpn


#测试mycat是否可以登录(可用任何客户机连接测试)
mysql -uroot -p123456 -h 10.0.1.164 -P8066


#主库建立mycat账户并授权(打通主库和mycat服务器的连接)
mysql> create user admin@'10.0.1.%' identified by '123456';
Query OK, 0 rows affected (0.01 sec)

mysql> grant all on *.* to admin@'10.0.1.%';
Query OK, 0 rows affected (0.00 sec)




5.在mycat 服务器上修改server.xml文件配置Mycat的连接信息

---------------------------------------------------------------

                        可修改的地方(按自己需求改)
---------------------------------------------------------------
vim /apps/mycat/conf/server.xml

root@centos8 ~]#vim /apps/mycat/conf/server.xml
...省略...
#修改下面行的8066改为3306复制到到独立非注释行(只适合mycat独占一个服务器,或者改其他端口,不然端口会冲突)
<property name="serverPort">3306</property>
<property name="handlelDistributedTransactions">0</property> #将上面行放在此行前面
#或者删除注释,并修改下面行的8066改为3306
<property name="serverPort">3306</property>
<property name="managerPort">9066</property>
<property name="idleTimeout">300000</property>
<property name="authTimeout">15000</property>
<property name="bindIp">0.0.0.0</property>
<property name="dataNodeIdleCheckPeriod">300000</property> #5 * 60 * 1000L; //连接空闲检查 删除#后面此部分
<property name="frontWriteQueueSize">4096</property> <property 
name="processors">32</property> #--> 删除#后面此部分
 .....
<user name="root">                                       #连接Mycat的用户名
   <property name="password">magedu</property>          #连接Mycat的密码
   <property name="schemas">TESTDB</property>           #数据库名要和schema.xml相对应
</user>
</mycat:server>
----------------------------------------------------------------


##配置server.xml
vim server.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- - - Licensed under the Apache License, Version 2.0 (the "License"); 
	- you may not use this file except in compliance with the License. - You 
	may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 
	- - Unless required by applicable law or agreed to in writing, software - 
	distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 
	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the 
	License for the specific language governing permissions and - limitations 
	under the License. -->
<!DOCTYPE mycat:server SYSTEM "server.dtd">
<mycat:server xmlns:mycat="http://io.mycat/">
	<system>
	<property name="useSqlStat">0</property>  <!-- 1为开启实时统计、0为关闭 -->
	<property name="useGlobleTableCheck">0</property>  <!-- 1为开启全加班一致性检测、0为关闭 -->

		<property name="sequnceHandlerType">2</property>
      <!--  <property name="useCompression">1</property>--> <!--1为开启mysql压缩协议-->
        <!--  <property name="fakeMySQLVersion">5.6.20</property>--> <!--设置模拟的MySQL版本号-->
	<property name="processorBufferChunk">5012</property>
	
	<property name="processors">16</property> 
	<property name="processorExecutor">16</property> 

		<!--默认为type 0: DirectByteBufferPool | type 1 ByteBufferArena-->
		<property name="processorBufferPoolType">0</property>
		<!--默认是65535 64K 用于sql解析时最大文本长度 -->
		<!--<property name="maxStringLiteralLength">65535</property>-->
		<!--<property name="sequnceHandlerType">0</property>-->
		<!--<property name="backSocketNoDelay">1</property>-->
		<!--<property name="frontSocketNoDelay">1</property>-->
		<!--<property name="processorExecutor">16</property>-->
		<!--
			<property name="serverPort">8066</property> <property name="managerPort">9066</property> 
			<property name="idleTimeout">300000</property> <property name="bindIp">0.0.0.0</property> 
			<property name="frontWriteQueueSize">4096</property> <property name="processors">32</property> -->
		<!--分布式事务开关,0为不过滤分布式事务,1为过滤分布式事务(如果分布式事务内只涉及全局表,则不过滤),2为不过滤分布式事务,但是记录分布式事务日志-->
		<property name="handleDistributedTransactions">0</property>
		
			<!--
			off heap for merge/order/group/limit      1开启   0关闭
		-->
		<property name="useOffHeapForMerge">1</property>

		<!--
			单位为m
		-->
		<property name="memoryPageSize">1m</property>

		<!--
			单位为k
		-->
		<property name="spillsFileBufferSize">1k</property>

		<property name="useStreamOutput">0</property>

		<!--
			单位为m
		-->
		<property name="systemReserveMemorySize">384m</property>


		<!--是否采用zookeeper协调切换  -->
		<property name="useZKSwitch">true</property>


	</system>
	
	<!-- 全局SQL防火墙设置 -->
	<!-- 
	<firewall> 
	   <whitehost>
	      <host host="127.0.0.1" user="mycat"/>
	      <host host="127.0.0.2" user="mycat"/>
	   </whitehost>
       <blacklist check="false">
       </blacklist>
	</firewall>
	-->
	

	<user name="admin">  #客户端连接mycat的账户
		<property name="password">123456</property>  #客户端连接mycat的密码
		<property name="schemas">zhangsan,gpsdb2020</property>
	</user>                 #这里的数据库可以指定具体那个,也可以默认mycat虚拟逻辑数据库


</mycat:server>








5.修改schema.xml实现读写分离策略

cd /apps/mycat/conf



##配置schema.xml
vim schema.xml

#最终文件内容
[root@mycat ~]#cat /apps/mycat/conf/schema.xml
[root@centos7mage conf]# cat schema.xml 
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">
	<schema name="gpsdb2020" checkSQLschema="false" sqlMaxLimit="100" dataNode="dn1"></schema>
	<schema name="zhangsan" checkSQLschema="false" sqlMaxLimit="100" dataNode="dn2"></schema>
	<dataNode name="dn1" dataHost="localhost1" database="gpsdb2020" />
	<dataNode name="dn2" dataHost="localhost1" database="zhangsan" />
	<dataHost name="localhost1" maxCon="500" minCon="20" balance="1" writeType="0" dbType="mysql" dbDriver="native" switchType="1"  slaveThreshold="100">
		<heartbeat>select user()</heartbeat>
		<writeHost host="master" url="10.0.1.164:3306" user="admin" password="123456">
		<readHost host="slave" url="10.0.1.165:3306" user="admin" password="123456" />
		</writeHost>
	</dataHost>
</mycat:schema>

#tips:读写分离的账号和密码,这里你可以在master上创建一个,也可以用主从复制的账号都可以,这里我自己测试的都可以



#重新启动mycat
[root@centos8 ~]#mycat restart






6.在后端主服务器创建用户并对mycat授权
[root@centos8 ~]#mysql -uroot -p
mysql> create database mycat;
mysql>GRANT ALL ON *.* TO 'admin'@'10.0.0.%' IDENTIFIED BY '123456' ;
mysql> flush privileges;


#tips:读写分离的账号和密码,这里你可以在master上创建一个,也可以用主从复制的账号都可以,这里我自己测试的都可以


7.在Mycat服务器上连接并测试

[root@centos7mage local]# mysql -uadmin -p123456 -h 10.0.1.164 -P8066

mysql> show databases;
+-----------+
| DATABASE  |
+-----------+
| gpsdb2020 |
| zhangsan  |
+-----------+
2 rows in set (0.00 sec)


#由于我们在配置文件指定了这个两个数据库,所以显示的就是这两个数据库,但是我们也可以用默认mycat的虚拟逻辑数据库(TESTDB),如果你没有这两个数据库的话,可以去创建一下-----|||create database zhangsan;create database gpsdb2020;





8.测试mycat读写分离

读---10.0.1.165
log-bin = mysql-bin
server-id=11

写---10.0.1.164

log-bin = mysql-bin
server-id=1

在任意一台客户端上连接mycat进行操作
mysql -uadmin -p123456 -h 10.0.1.164 -P8066

读操作----返回10.0.1.165的serverid为11,如果是11,即为成功
#select @@server_id;

mysql> select @@server_id;
+-------------+
| @@server_id |
+-------------+
|          11 |
+-------------+
1 row in set (0.00 sec)



写操作----返回10.0.1.164的serverid为1,如果是1,即为成功
#begin;select @@server_id;commit;
mysql> begin;select @@server_id;commit;
Query OK, 0 rows affected (0.00 sec)

+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
1 row in set (0.01 sec)








9.通过通用日志确认实现读写分离

在mysql中查看通用日志

show variables like 'general_log';  #查看日志是否开启
set global general_log=on;    #开启日志功能
show variables like 'general_log_file'; #查看日志文件保存位置
set global general_log_file='tmp/general.log'; #设置日志文件保存位置



在主和从服务器分别启用通用日志,查看读写分离
[root@centos8 ~]#vim /etc/my.cnf
[mysqld]
general_log=ON
[root@centos8 ~]#service mysqld restart
[root@centos8 ~]#tail -f /var/lib/mysql/centos8.log



10.停止从节点,MyCAT自动调度读请求至主节点
[root@slave ~]#service mysqld stop
[root@client ~]#mysql -uadmin -p123456 -h10.0.1.164 -P8066
MySQL [(none)]> select @@server_id;
+-------------+
| @@server_id |
+-------------+
|          1 |
+-------------+
1 row in set (0.00 sec)
MySQL [(none)]> 


#停止主节点,MyCAT不会自动调度写请求至从节点
MySQL [TESTDB]> insert teachers values(5,'wang',30,'M');
ERROR 1184 (HY000): java.net.ConnectException: Connection refused



11.MyCAT对后端服务器的健康性检查方法select user()
#开启通用日志
[root@master ~]#mysql
mysql> set global  general_log=1;
[root@slave ~]#mysql
mysql> set global  general_log=1;
#查看通用日志
[root@master ~]#tail -f /data/mysql/master.log 
/usr/libexec/mysqld, Version: 8.0.17 (Source distribution). started with:
Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command   Argument
2021-02-22T08:52:57.086198Z   17 Query select user()
2021-02-22T08:53:07.086340Z   24 Query select user()
2021-02-22T08:53:17.086095Z   16 Query select user()
2021-02-22T08:53:27.086629Z   18 Query select user()
[root@slave ~]#tail -f /data/mysql/slave.log 
/usr/libexec/mysqld, Version: 8.0.17 (Source distribution). started with:
Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command   Argument
2021-02-22T08:46:01.437376Z   10 Query select user()
2021-02-22T08:46:11.438172Z   11 Query select user()
2021-02-22T08:46:21.437458Z   12 Query select user()
2021-02-22T08:46:31.437742Z   13 Query select user()

















mycat故障实例解决

故障1

[root@centos7mage bin]# tail -f /apps/mycat/logs/wrapper.log 
INFO   | jvm 4    | 2024/04/15 11:14:29 | sun.management.AgentConfigurationError: java.net.MalformedURLException: Local host name unknown: java.net.UnknownHostException: centos7mage: centos7mage: Name or service not known
INFO   | jvm 4    | 2024/04/15 11:14:29 | 	at sun.management.jmxremote.ConnectorBootstrap.startRemoteConnectorServer(ConnectorBootstrap.java:482)
INFO   | jvm 4    | 2024/04/15 11:14:29 | 	at sun.management.Agent.startAgent(Agent.java:262)
INFO   | jvm 4    | 2024/04/15 11:14:29 | 	at sun.management.Agent.startAgent(Agent.java:452)
INFO   | jvm 4    | 2024/04/15 11:14:29 | Caused by: java.net.MalformedURLException: Local host name unknown: java.net.UnknownHostException: centos7mage: centos7mage: Name or service not known
INFO   | jvm 4    | 2024/04/15 11:14:29 | 	at javax.management.remote.JMXServiceURL.<init>(JMXServiceURL.java:289)
INFO   | jvm 4    | 2024/04/15 11:14:29 | 	at javax.management.remote.JMXServiceURL.<init>(JMXServiceURL.java:253)
INFO   | jvm 4    | 2024/04/15 11:14:29 | 	at sun.management.jmxremote.ConnectorBootstrap.exportMBeanServer(ConnectorBootstrap.java:763)
INFO   | jvm 4    | 2024/04/15 11:14:29 | 	at sun.management.jmxremote.ConnectorBootstrap.startRemoteConnectorServer(ConnectorBootstrap.java:470)
INFO   | jvm 4    | 2024/04/15 11:14:29 | 	... 2 more
STATUS | wrapper  | 2024/04/15 11:14:34 | Launching a JVM...
ERROR  | wrapper  | 2024/04/15 11:14:44 | JVM exited while loading the application.
INFO   | jvm 5    | 2024/04/15 11:14:44 | Error: Exception thrown by the agent : java.net.MalformedURLException: Local host name unknown: java.net.UnknownHostException: centos7mage: centos7mage: Name or service not known
INFO   | jvm 5    | 2024/04/15 11:14:44 | sun.management.AgentConfigurationError: java.net.MalformedURLException: Local host name unknown: java.net.UnknownHostException: centos7mage: centos7mage: Name or service not known
INFO   | jvm 5    | 2024/04/15 11:14:44 | 	at sun.management.jmxremote.ConnectorBootstrap.startRemoteConnectorServer(ConnectorBootstrap.java:482)
INFO   | jvm 5    | 2024/04/15 11:14:44 | 	at sun.management.Agent.startAgent(Agent.java:262)
INFO   | jvm 5    | 2024/04/15 11:14:44 | 	at sun.management.Agent.startAgent(Agent.java:452)
INFO   | jvm 5    | 2024/04/15 11:14:44 | Caused by: java.net.MalformedURLException: Local host name unknown: java.net.UnknownHostException: centos7mage: centos7mage: Name or service not known
INFO   | jvm 5    | 2024/04/15 11:14:44 | 	at javax.management.remote.JMXServiceURL.<init>(JMXServiceURL.java:289)
INFO   | jvm 5    | 2024/04/15 11:14:44 | 	at javax.management.remote.JMXServiceURL.<init>(JMXServiceURL.java:253)
INFO   | jvm 5    | 2024/04/15 11:14:44 | 	at sun.management.jmxremote.ConnectorBootstrap.exportMBeanServer(ConnectorBootstrap.java:763)
INFO   | jvm 5    | 2024/04/15 11:14:44 | 	at sun.management.jmxremote.ConnectorBootstrap.startRemoteConnectorServer(ConnectorBootstrap.java:470)
INFO   | jvm 5    | 2024/04/15 11:14:44 | 	... 2 more
FATAL  | wrapper  | 2024/04/15 11:14:44 | There were 5 failed launches in a row, each lasting less than 300 seconds.  Giving up.
FATAL  | wrapper  | 2024/04/15 11:14:44 |   There may be a configuration problem: please check the logs.
STATUS | wrapper  | 2024/04/15 11:14:44 | <-- Wrapper Stopped






解决:centos系统未做解析
vim /etc/hosts
127.0.0.1   centos7mage localhost

重新启动mycat





故障2 
[root@centos7mage logs]# cat wrapper.log 
STATUS | wrapper  | 2024/04/15 16:20:54 | --> Wrapper Started as Daemon
STATUS | wrapper  | 2024/04/15 16:20:54 | Launching a JVM...
INFO   | jvm 1    | 2024/04/15 16:20:55 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
INFO   | jvm 1    | 2024/04/15 16:20:55 |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
INFO   | jvm 1    | 2024/04/15 16:20:55 | 
INFO   | jvm 1    | 2024/04/15 16:20:56 | MyCAT Server startup successfully. see logs in logs/mycat.log
STATUS | wrapper  | 2024/04/15 16:35:13 | TERM trapped.  Shutting down.
STATUS | wrapper  | 2024/04/15 16:35:14 | <-- Wrapper Stopped
STATUS | wrapper  | 2024/04/15 17:01:36 | --> Wrapper Started as Daemon
STATUS | wrapper  | 2024/04/15 17:01:36 | Launching a JVM...
INFO   | jvm 1    | 2024/04/15 17:01:37 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
INFO   | jvm 1    | 2024/04/15 17:01:37 |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
INFO   | jvm 1    | 2024/04/15 17:01:37 | 
INFO   | jvm 1    | 2024/04/15 17:01:37 | 
INFO   | jvm 1    | 2024/04/15 17:01:37 | WrapperSimpleApp: Encountered an error running main: java.lang.ExceptionInInitializerError
INFO   | jvm 1    | 2024/04/15 17:01:37 | java.lang.ExceptionInInitializerError
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.MycatStartup.main(MycatStartup.java:53)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at java.lang.reflect.Method.invoke(Method.java:498)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at org.tanukisoftware.wrapper.WrapperSimpleApp.run(WrapperSimpleApp.java:240)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at java.lang.Thread.run(Thread.java:750)
INFO   | jvm 1    | 2024/04/15 17:01:37 | Caused by: io.mycat.config.util.ConfigException: org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 2; Element type "dataHost" must be followed by either attribute specifications, ">" or "/>".
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.config.loader.xml.XMLSchemaLoader.load(XMLSchemaLoader.java:121)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.config.loader.xml.XMLSchemaLoader.<init>(XMLSchemaLoader.java:78)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.config.loader.xml.XMLSchemaLoader.<init>(XMLSchemaLoader.java:82)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.config.ConfigInitializer.<init>(ConfigInitializer.java:76)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.config.MycatConfig.<init>(MycatConfig.java:72)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.MycatServer.<init>(MycatServer.java:178)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.MycatServer.<clinit>(MycatServer.java:121)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	... 7 more
INFO   | jvm 1    | 2024/04/15 17:01:37 | Caused by: org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 2; Element type "dataHost" must be followed by either attribute specifications, ">" or "/>".
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:178)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:399)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:326)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1466)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.seekCloseOfStartTag(XMLDocumentFragmentScannerImpl.java:1393)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1323)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2783)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:601)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:504)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:841)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:770)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:338)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.config.util.ConfigUtil.getDocument(ConfigUtil.java:115)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	at io.mycat.config.loader.xml.XMLSchemaLoader.load(XMLSchemaLoader.java:111)
INFO   | jvm 1    | 2024/04/15 17:01:37 | 	... 13 more
STATUS | wrapper  | 2024/04/15 17:01:39 | <-- Wrapper Stopped
STATUS | wrapper  | 2024/04/15 17:06:44 | --> Wrapper Started as Daemon
STATUS | wrapper  | 2024/04/15 17:06:44 | Launching a JVM...
INFO   | jvm 1    | 2024/04/15 17:06:44 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
INFO   | jvm 1    | 2024/04/15 17:06:44 |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
INFO   | jvm 1    | 2024/04/15 17:06:44 | 
STATUS | wrapper  | 2024/04/15 17:06:47 | <-- Wrapper Stopped
STATUS | wrapper  | 2024/04/15 17:09:11 | --> Wrapper Started as Daemon
STATUS | wrapper  | 2024/04/15 17:09:11 | Launching a JVM...
INFO   | jvm 1    | 2024/04/15 17:09:12 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
INFO   | jvm 1    | 2024/04/15 17:09:12 |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
INFO   | jvm 1    | 2024/04/15 17:09:12 | 
STATUS | wrapper  | 2024/04/15 17:09:14 | <-- Wrapper Stopped
[root@centos7mage logs]# tail wrapper.log 
INFO   | jvm 1    | 2024/04/15 17:09:12 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
INFO   | jvm 1    | 2024/04/15 17:09:12 |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
INFO   | jvm 1    | 2024/04/15 17:09:12 | 
STATUS | wrapper  | 2024/04/15 17:09:14 | <-- Wrapper Stopped
STATUS | wrapper  | 2024/04/15 17:17:08 | --> Wrapper Started as Daemon
STATUS | wrapper  | 2024/04/15 17:17:09 | Launching a JVM...
INFO   | jvm 1    | 2024/04/15 17:17:09 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
INFO   | jvm 1    | 2024/04/15 17:17:09 |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
INFO   | jvm 1    | 2024/04/15 17:17:09 | 
STATUS | wrapper  | 2024/04/15 17:17:12 | <-- Wrapper Stopped
[root@centos7mage logs]# tail -f wrapper.log 
INFO   | jvm 1    | 2024/04/15 17:09:12 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
INFO   | jvm 1    | 2024/04/15 17:09:12 |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
INFO   | jvm 1    | 2024/04/15 17:09:12 | 
STATUS | wrapper  | 2024/04/15 17:09:14 | <-- Wrapper Stopped
STATUS | wrapper  | 2024/04/15 17:17:08 | --> Wrapper Started as Daemon
STATUS | wrapper  | 2024/04/15 17:17:09 | Launching a JVM...
INFO   | jvm 1    | 2024/04/15 17:17:09 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
INFO   | jvm 1    | 2024/04/15 17:17:09 |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
INFO   | jvm 1    | 2024/04/15 17:17:09 | 
STATUS | wrapper  | 2024/04/15 17:17:12 | <-- Wrapper Stopped


解决:生产环境中mycat一般是独占一台服务器,如果你在mysql服务器配置,要修改mycat的端口为3306,这里就不可以了,因为原先的3306已经给mysql用了,mycat也修改为3306的话,启动mycat就会冲突,只要不与3306冲突的话,就可以的,生产环境可以设置3306,这里就就默认原来的





mycat常见故障解决:

01 mycat--server.xml配置文件有误
02 mycat-- schema.xml 配置文件有误
03 防火墙问题 端口未放行
04 端口冲突
05 mycat账号密码不对或为授权




9.keepalived+mycat高可用

#步骤
环境:虚拟机
mycat服务器1 10.0.1.164
mycat服务器2 10.0.1.165



1关闭防火墙
systemctl stop firewalld
setenforce 0
时间同步


2.安装jdk
yum install java-1.8.0-openjdk* -y
#如果yum源有的话,也可以用yum安装
JDK8: 链接: https://pan.baidu.com/s/1sQhSR5GgmxB3STpihOqCAw 提取码: 0b6l
链接: https://pan.baidu.com/s/1vVXfDwyaI8-P12-eYrzP4w?pwd=1122 提取码: 1122 


3.上传或下载mycat


链接: https://pan.baidu.com/s/1NoVIjHV9ivPm6tzZqckbdw?pwd=1122 提取码: 1122 


4.解压启动mycat

#解压到指定目录(或者随意)
mkdir -p /apps 
tar zxvf Mycat-server-1.6.7.4-release-20200105164103-linux.tar.gz 

#配置环境变量
echo 'PATH=/apps/mycat/bin:$PATH' > /etc/profile.d/mycat.sh
source /etc/profile.d/mycat.sh

#启动mycat
mycat stop  停止
mycat start  启动
mycat restart  重启


#启动日志状态
cd /apps/mycat/logs
tail -f wrapper.log

#代表启动成功
tips:INFO   | jvm 1    | 2024/04/15 18:55:38 | MyCAT Server startup successfully. see logs in logs/mycat.log



#查看端口号
ss -tulpn
netstat -tulpn

#主库建立mycat账户并授权(打通主库和mycat服务器的连接)
mysql> create user admin@'10.0.1.%' identified by '123456';
Query OK, 0 rows affected (0.01 sec)

mysql> grant all on *.* to admin@'10.0.1.%';
Query OK, 0 rows affected (0.00 sec)


#测试mycat是否可以登录(可用任何客户机连接测试)
mysql -uadmin -p123456 -h 10.0.1.164 -P8066
mysql -uadmin -p123456 -h 10.0.1.165 -P8066







5.安装keepalived(mycat1/mycat2)
yum -y install keepalived
 systemctl start keepalived.service 
 systemctl status keepalived.service



6.配置高可用(mycat1/mycat2)
 vim /etc/keepalived/keepalived.conf

mycat1配置:
! Configuration File for keepalived
   
    global_defs {
        router_id lb01    #高可用集群标识 不能冲突
    }
   
    vrrp_instance it {       #家族名字
        state MASTER          #身份
        interface eth0        #网卡名称 这里要与你的网卡名要一样
        virtual_router_id 51    #身份信息 两台要一致
        priority 150           #优先级   数字越高 等级越大
        advert_int 1           #组播发送间隔时间
        authentication {       #人证过程
            auth_type PASS
            auth_pass 1111
        }
        virtual_ipaddress {
            10.0.1.100/24          #配置虚拟vip
        }
    }
    
    #重启keepalived
systemctl restart keepalived

    
    
  mycat2配置
  vim /etc/keepalived/keepalived.conf
  ! Configuration File for keepalived
   
    global_defs {
        router_id lb02    #高可用集群标识 不能冲突
    }
   
    vrrp_instance it {       #家族名字
        state MASTER          #身份
        interface eth0        #网卡名称 这里要与你的网卡名要一样
        virtual_router_id 51    #身份信息 两台要一致
        priority 100           #优先级   数字越高 等级越大
        advert_int 1           #组播发送间隔时间
        authentication {       #人证过程
            auth_type PASS
            auth_pass 1111
        }
        virtual_ipaddress {
            10.0.1.100/24          #配置虚拟vip
        }
    }

#重启keepalived
systemctl restart keepalived


7.测试虚拟ip是否可以登录
   mysql -uadmin -p123456 -h 10.0.1.100(测试虚拟ip是否可以登录)
   
   


8.测试高可用(是否有效)

正常状态前
10.0.1.164(keepalived主)
mycat1:
ip  a
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:d0:18:02 brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.164/24 brd 10.255.255.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet 10.0.1.169/24 brd 10.0.1.255 scope global secondary dynamic eth0
       valid_lft 1774sec preferred_lft 1774sec
    inet 10.0.1.100/24 scope global secondary eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fed0:1802/64 scope link 
       valid_lft forever preferred_lft forever



10.0.1.165(keepalived备)
mycat2:
ip a
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:cc:4e:6b brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.165/24 brd 10.255.255.255 scope global eth0
       valid_lft forever preferred_lft forever




需求:因不可抗力原因,mycat1keepalived高可用突然宕机了,
目的:把vip自动漂移到mycat2上
实现效果:最终实现即使mycat1不可以运行了,但是mycat2自动接管mycat1服务






具体效果:
mycat1:

[root@centos7mage apps]# systemctl stop keepalived.service 
[root@centos7mage apps]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:d0:18:02 brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.164/24 brd 10.255.255.255 scope global eth0
       valid_lft forever preferred_lft forever


mycat2:
[root@centos7mage ~]# ip a
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:cc:4e:6b brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.165/24 brd 10.255.255.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet 10.0.1.170/24 brd 10.0.1.255 scope global secondary dynamic eth0
       valid_lft 1419sec preferred_lft 1419sec
    inet 10.0.1.100/24 scope global secondary eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fecc:4e6b/64 scope link 
       valid_lft forever preferred_lft forever
       
       
       




10.备份数据库(生产环境shell备份数据库)


#步骤



#!/bin/bash
#备份数据库
user=nwq
password=Hello123
datatime= date '+%Y-%m-%d_%T'
echo "数据库备份时间...........$datatime">>/data/backup/mnt/back.log
/usr/local/mysql/bin/mysqldump -u$user -p$password hellodb |gzip > /data/backup/${datatime}_hellodb.gz 2>/dev/null

echo "数据库结束时间...........$datatime">>/data/backup/mnt/back.log






需求:每天晚上夜里00点执行数据库备份
可结合定时任务(每天夜里00点执行备份数据库)

crontab -e

0 0 * * * /bin/bash /data/backup/mysqlbf.sh >/dev/null 2>&1




##不知道自己的msyqldump命令在哪个位置的话,可以用which mysqldump













11.生产环境备份数据库注意事项

11.什么时间执行数据库备份?

夜里2点
定时任务 0 2 * * * /data/backup/mysqlbf.sh >>/dev/null 2>&1



11.2 100G备份数据库需要多久?
正常情况下40分钟左右



基本上每家公司时间都不一样
影响因素:cpu 硬盘 内存
10.3 200G备份数据库需要多久?
1个小时左右


posted @ 2024-04-15 21:58  三思博客  阅读(27)  评论(0编辑  收藏  举报