数据库作业-1

数据库作业-1

0.mysql5.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 .增删改查sql语句写一下 :

写出Mysql创建HRM数据库的语句,如果HRM数据库存在,删除它重建;并在HRM数据库创建一张user表,表包含自增量id,以及姓名name(25个字符串)

#创建HRM数据
create database HRM;

#删除已经存在的HRM数据库
drop database if exists HRM;
drop database HRM;
 
#切换到HRM数据库
use HRM;

#创建user表
create table if  not exists user (id int auto_increment primary key, name varchar(25) not null);



#查看某个user表
show columns from user;
describe user;


#查看所有用户和权限
select user, host from mysql.user;


#刷新权限
flush privileges;


#重新设置
reset master;
reset master all;

#停止数据库/锁库
stop slave;


#查看slave状态
show slave status\G;

#查看主master状态
show master status;

#查看当前所有数据库
show databases;

#查看当前所有表
show tables;



2.公司单机数据库延伸主从架构 实施



环境:虚拟机
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.主主模式实战演示

#步骤

环境:虚拟机

主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)



4.数据库MHA 高可用实施


#步骤
环境:虚拟机
主: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






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









5.数据库架构延伸 实施读写分离 一个主库负责写 一个从库负责读取


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()


















6.给开发建立一个用户kf 密码Hello88 授权只能select读取权限

#创建用户kf--密码Hello88
create user 'kf'@'%' indentified by 'Hello88';

#授予select权限
grant select on HRM.* to 'kf'@'%';

#刷新配置
flush privileges;






7.数据库备份命令:

mysqldump -u root -pHello88 HRM > HRM_backup.sql



8 写一个脚本数据库备份脚本 夜里2点执行


#步骤



#!/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













项目经历

项目方案 3:Mysql 读写分离架构实施项目背景:  (这个项目会出现到你的简历上)重点实战

公司业务随着用户不断增加,数据库无法抗住大并发,经常会造成 mysql 锁表情况发生,为了更好提升用户的体验,对数据库架构进行调整
项目实施:
1、在原有的 mysql 主从架构基础,进行调整。
2、新增服务器一台安装 mycat,进行读写分离配置
3、测试环境测试没有问题时候,在业务量低谷的时候,修改代码连接 mycat
4、实现业务读写分离项目结果:
好处:增加数据库服务器,压力随之分摊到几个服务器中,减小数据库压力通过读写分离架构实施,解决用户量大造成数据库有压力问题,业务效率大大提高

坏处:硬件成本大 数据库主从问题哈希一致性问题 单点故障问题
posted @ 2024-04-15 21:58  三思博客  阅读(16)  评论(0编辑  收藏  举报