一、MySQL概述
MySQL是一个**关系型数据库管理系统****,**由瑞典MySQL AB 公司开发,属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的 RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件之一。
MySQL是一种关系型数据库管理系统,关系数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库内,这样就增加了速度并提高了灵活性。
MySQL所使用的 SQL 语言是用于访问数据库的最常用标准化语言。MySQL 软件采用了双授权政策,分为社区版和商业版,由于其体积小、速度快、总体拥有成本低,尤其是开放源码这一特点,一般中小型网站的开发都选择 MySQL 作为网站数据库。
1.1 关系型数据库(RDBMS)
关系数据库管理系统(Relational Database Management System:RDBMS)是指包括相互联系的逻辑组织和存取这些数据的一套程序 (数据库管理系统软件)。关系数据库管理系统就是管理关系数据库,并将数据逻辑组织的系统。即采用二维表格组织数据的数据库。
常见关系型数据库
Oracle、mysql、DB2(IBM)、SQL server(微软)
1.1.1 RDBMS特点
事务的一致性
事务:由一条或多条sql语句组成,在事务中的操作,这些sql语句要么都成功执行,要么都不执行。
事务特点(ACID):
原子性(Atomicity): 事务中的全部操作在数据库中是不可分割的,要么全部完成,要么均不执行。 一致性(Consistency): 指事务必须使数据库从一个致性状态变换到另一个一致性状态,也就是说一个事务执行之前和执行之后都必须处于一致性状态,不能破坏关系数据的完整性以及业务逻辑上的一致性。 隔离性(lsolation): 一个事务的执行不受其他事务的干扰,事务执行的中间结果对其他事务必须是透明的。隔离性是当多个用户并发访问数据库时,比如操作同一张表时,数据库为每一个用户开启的事务,不能被其他事务 的操作所干扰,多个并发事务之间要相互隔离。 持久性(Durability):持久性是指一个事务一旦被提交了,那么对数据库中的数据的改变就是永久性的,即便是在数据库系统遇到故障的情况下也不会丢失事务的操作。场景:对数据一致性要求较高;典型就是银行及其他支付系统
1.2 MySQL数据库版本
社区版: MySQL Community Edition(gpl) 1.可以看做是企业版的广泛体验版(小白鼠版)”,未经各个专有系统平台的压力测试和性能测试 2.基于GPL协议发布,可以随意下载使用 3没有任何官方技术支持服务
企业版: MySQL Enterprise Edition(commercial) 1.提供了比较全面的高级功能、管理工具及技术支持 2.安全性、稳定性、可扩展性比较好
集群版: MySQL Cluster CGE(commercial)
二、MySQL安装
2.1 MySQL的几种安装方式
二进制安装
rpm安装 :MySQL-server-5.6.31-1.el7.x86_64.rpm (需在特定linux版本下安装)
基于glibc版本安装:mysql-5.6.30-linux-glibc2.5-x86_64.tar.gz(依赖glibc库,可以安装在通用的linux系统下)
源码安装
mysql-5.6.36.tar.gz (通用linux下都可以编译安装)
2.2 安装方式区别
| 安装方式 | 优点 | 缺点 |
|---|---|---|
| rpm | 安装卸载简单 | 可定制性差 |
| glibc | 可定制性相比rpm包灵活 | 安装相比rpm包复杂些,需要手动初始化数据库 |
| 源码安装 | 可定制性最强,根据需求和功能功能定制 | 安装麻烦,需要手动初始化数据库 |
2.3 glibc安装
2.3.1 环境创建
[root@localhost ~]# yum -y remove mariadb*
# 安装前先卸载系统中自带的有关mariadb有关软件,否则会影响下面安装
[root@localhost ~]# mkdir /apps/
# 存放MySQL软件包目录
[root@localhost ~]# mkdir -p /data/mysql
# 存放MySQL数据目录
2.3.2下载glibc包
[root@localhost ~]# cd /opt/
[root@localhost opt]# wget https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.31-linux-glibc2.12-x86_64.tar.gz
[root@localhost opt]# tar zxf mysql-5.7.31-linux-glibc2.12-x86_64.tar.gz -C /apps/
[root@localhost opt]# mv /apps/mysql-5.7.31-linux-glibc2.12-x86_64/ /apps/mysql
[root@localhost opt]# cd /apps/mysql
2.3.3 创建MySQL运行用户
[root@localhost mysql]# useradd -s /bin/false -M mysql
2.3.4 目录授权
[root@localhost mysql]# chown -R mysql. /apps/mysql/
[root@localhost mysql]# chown -R mysql. /data/mysql/
2.3.5 初始化数据库
- 添加mysql工具到环境变量
[root@localhost mysql]# vim /etc/profile
export PATH=/apps/mysql/bin:$PATH
[root@localhost mysql]# source /etc/profile
- 配置文件
[root@localhost mysql]# vim /etc/my.cnf
[mysqld]
user=mysql
basedir=/apps/mysql # 软件基础目录
datadir=/data/mysql # 数据存放目录
server_id=6 # 识别ID
port=3306 # 端口
socket=/apps/mysql/mysql.sock # socket文件路径
symbolic_links=0
[mysql]
socket=/apps/mysql/mysql.sock
prompt=3306 [\\d]>
- 初始化数据库
[root@localhost mysql]# mysqld --initialize --user=mysql --basedir=/apps/mysql --datadir=/data/mysql
# 初始化完成后会生成一个临时密码,并在日志中会记录一份.密码复杂度12位、字符混乱组合,密码过期时间180天
[root@localhost mysql]# mysqld --initialize-insecure --user=mysql --basedir=/apps/mysql --datadir=/data/mysql
# 无密码及密码复杂度初始化
# 与5.6 初始化区别 /apps/mysql/scripts/mysql_install_db
2.3.6 配置启动脚本
[root@localhost mysql]# cp support-files/mysql.server /etc/init.d/mysqld
# 复制启动脚本到service管理目录中
[root@localhost mysql]# service mysqld start
# 启动数据
2.3.7 安装出错处理
mysqld: error while loading shared libraries: libaio.so.1: cannot open shared object file: No such file or directory
[root@k9k5n4vt4qczceww mysql]# yum -y install libaio
2.4 源码安装
官方手册地址:https://dev.mysql.com/doc/refman/5.7/en/source-installation.html
2.4.1 编译环境准备
由于MySQL被Oracle收购,将make改为了Oracle的Cmake。所以需要按照Cmake
[root@localhost ~]# yum -y remove mariadb*
# 安装前先卸载系统中自带的有关mariadb有关软件,否则会影响下面安装
[root@localhost ~]# yum -y install cmake gcc gcc-c++
2.4.2 编译配置选项
| 配置选项 | 描述 | 默认值 | 建议值 |
|---|---|---|---|
| CMAKE_INSTALL_PREFIX | 安装路径(basedir) | /usr/local/mysql | 根据需求 |
| MYSQL_DATADIR | 数据目录(datadir) | 根据需求 | |
| SYSCONFDIR | 配置文件(my.cnf)路径 | /etc | |
| MYSQL_TCP_PORT | tcp/ip端口号 | 3306 | 非默认端口 |
| MYSQL_UNIX_ADDR | 套接字路径 | /tmp/mysql.sock | $basedir/ |
| DEFAULT_CHARSET | 默认字符集 | latin1 | utf8mb4 |
| DEFAULT_COLLATION | 默认校验规则 | latin1_swedish_ci | utf8mb4_general_ci |
| WITH_EXTRA_CHARSETS | 额外扩展字符集 | all | all |
| ENABLED_LOCAL_INFILE | 是否启用本地加载外部数据文件功能 | OFF | 建议开启 |
说明:配置选项为bool值类型的,如 ENABLED_LOCAL_INFILE,默认值为OFF,要开启的话:ENABLED_LOCAL_INFILE = 1进行开启
# 重点:存储引擎配置选项
WITH_xxx_STORAGE_ENGINE #将存储引擎xxx静态编译到服务器中
xxx可选值为以下
InnoDB:将InnoDB存储引擎插件构建为静态模块编译到服务器中。建议进行编译
Partition:是否支持分区。建议开启
Federated:本地数据库是否可以远程访问mysql数据
Blackhole:黑洞存储引擎,接受数据,但不存储,直接丢弃
Myisam:将MYISAM存储引擎静态编译到服务器中。建议开启
2.4.3 按照步骤
下载软件包并解压到/opt目录中
[root@localhost ~]# wget https://downloads.mysql.com/archives/get/p/23/file/mysql-5.6.36.tar.gz [root@localhost ~]# tar zxf mysql-5.6.36.tar.gz -C /opt/MySQL依赖安装
[root@localhost ~]# yum -y install ncurses-devel编译检测
[root@localhost ~]# cd /opt/mysql-5.6.36/ [root@localhost mysql-5.6.36]# cmake \ -DCMAKE_INSTALL_PREFIX=/apps/mysql \ -DMYSQL_DATADIR=/apps/mysql/data \ -DSYSCONFDIR=/etc \ -DMYSQL_TCP_PORT=3306 \ -DMYSQL_UNIX_ADDR=/apps/mysql/mysql.sock \ -DDEFAULT_CHARSET=utf8mb4 \ -DDEFAULT_COLLATION=utf8mb4_general_ci \ -DWITH_EXTRA_CHARSETS=all \ -DENABLED_LOCAL_INFILE=1 \ -DWITH_INNOBASE_STORAGE_ENGINE=1 \ -DWITH_PARTITION_STORAGE_ENGINE=1 \ -DWITH_FEDERATED_STORAGE_ENGINE=1 \ -DWITH_MYISAM_STORAGE_ENGINE=1 \ -DWITH_BLACKHOLE_STORAGE_ENGINE=1编译
[root@localhost mysql-5.6.36]# make -j 4 # -j 参数指定编译线程数,可加快编译速度安装
[root@localhost mysql-5.6.36]# make install
2.4.4 安装完成后配置
初始化数据库
[root@localhost ~]# useradd -s /bin/false -M mysql # 创建MySQL运行用户,/bin/false为完全禁止此用户登录包括登录服务。/sbin/nologin只是只是为不能登录系统,但可用账户登录软件服务。 [root@localhost ~]# cd /apps/mysql [root@localhost mysql]# chown -R mysql. /apps/mysql # 修改目录权限 [root@localhost mysql]# bin/mysqld --initialize --user=mysql --datadir=/apps/mysql/data --basedir=/apps/mysql # 初始化数据库运行用户为mysql,创建数据库基础数据,并且为root用户创建一个临时密码初始化失败报错:
FATAL ERROR: please install the following Perl modules before executing /usr/bin/mysql_install_db: Data::Dumper
安装perl-Module-Install即可(最小化安装系统可能报此错误)
[root@localhost mysql]# yum -y install perl-Module-Install
复制启动脚本
[root@localhost mysql]# cp support-files/mysql.server /etc/init.d/mysqld以下为systemctl启动脚本/usr/lib/systemd/system/mysqld.service
[root@localhost mysql]# vim /etc/systemd/system/mysqld.service [Unit] Description=MySQL Server Documentation=man:mysqld(8) Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html After=network.target After=syslog.target [Install] WantedBy=multi-user.target [Service] User=mysql Group=mysql ExecStart=/apps/mysql/bin/mysqld --defaults-file=/etc/my.cnf LimitNOFILE = 5000 [root@localhost mysql]# systemctl daemon-reload mysqld启动数据库
默认启动将会读取/etc/my.cnf配置文件,修改my.cnf配置文件
# 配置文件详解 [mysqld] user=mysql basedir=/apps/mysql # 软件基础目录 datadir=/data/mysql # 数据存放目录 server_id=10 # 识别ID port=3306 # 端口 socket=/apps/mysql/mysql.sock # socket文件路径 # Disabling symbolic-links is recommended to prevent assorted security risks symbolic_links=0 # Settings user and group are ignored when systemd is used. # If you need to run mysqld under a different user or group, # customize your systemd unit file for mariadb according to the # instructions in http://fedoraproject.org/wiki/Systemd [mysql] socket=/apps/mysql/mysql.sock prompt=3306 [\\d]>[root@localhost mysql]# service msyqld start Starting MySQL. SUCCESS!设置root密码 默认源码安装的mysql没有设置root密码,使用以下命令设置密码
[root@localhost mysql]# /apps/mysql/bin/mysqladmin -u root password '123' # 要在服务启动并且root用户没有密码才可使用此命令设置密码
2.5 MySQL启动脚本配置总结
方法一
[root@localhost mysql]# cp support-files/mysql.server /etc/init.d/mysqld # 复制启动脚本到service管理目录中 [root@localhost mysql]# service mysqld start # 启动数据方法二
[root@localhost mysql]# vim /etc/systemd/system/mysqld.service [Unit] Description=MySQL Server Documentation=man:mysqld(8) Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html After=network.target After=syslog.target [Install] WantedBy=multi-user.target [Service] User=mysql Group=mysql ExecStart=/apps/mysql/bin/mysqld --defaults-file=/etc/my.cnf LimitNOFILE=5000 [root@localhost mysql]# systemctl daemon-reload mysqld
2.6 MySQL数据库管理工具
mysql
mysql命令行工具,一般用来连接访问mysql数据库
语法: mysql [options] [db_name]
参数:
-u ,--user=name 指定数据库用户名
-p,--password 指定登录密码,一定要放到最后面
-h,--host=name 指定数据库的主机地址
-P,--port=xx 指定数据库的端口号
-S,--socket=name 指定socket文件
-e,--execute-name 使用非交互式操作(在mysql终端执行sql语句)
mysqladmin
mysqladmin命令是MySQL服务器管理任务的客户端工具,它可以检查MySQL服务器的配置和当前工作状态,创建和删除数据库,创建用户和修改用户密码等操作。
语法:mysqladmin [options] [command] 参数: reload:重载授权表 shutdown:停止服务器 start-slave:开启从服务器的复制 status:显示服务器状态信息 variables:显示服务器系统变量及其值 processlist:显示活动服务器线程的列表 password new-password:设置密码
2.7 MySQL配置文件
mysql启动读取配置文件顺序
[root@localhost ~]# mysql --verbose --help|grep my.cnf
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/my.cnf /etc/mysql/my.cnf /usr/local/mysql/etc/my.cnf ~/.my.cnf
# 默认情况下,MySQL启动时会依次读取以上配置文件,如有重复选项,会以最后一个文件设置为准。但是如果启动时加入了--defaults-file=xxx时,以上所有文件都不会读取。
# 配置文件详解
[mysqld]
user=mysql
basedir=/apps/mysql #软件基础目录
datadir=/data/mysql #数据存放目录
server_id=10 #识别ID
port=3306 #端口
socket=/apps/mysql/mysql.sock #socket文件路径
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic_links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
[mysql]
socket=/apps/mysql/mysql.sock
prompt=3306 [\\d]>
配置文件语法:
[标签]
配置项=xxx
# 标签类型:服务端、客户端
# 服务器端标签:[mysqld]、[mysqld_safe]、[server]
# 客户端标签:[mysql]、[mysqldump]、[client]
2.8 root密码修改
[root@localhost mysql]# mysqladmin -u root -p password '123'
三、MySQL体系结构与管理
3.1 C/S(客户端/服务端)模型
3.2 MySQL连接方式
参数: -u 用户
-p 密码
-h IP
-P 端口
-S socket文件
-e 免交互式执行命令
< 导入SQL脚本
- 基于TCP/IP连接方式(远程、本地)
[root@localhost ~]# mysql -u root -p -h 192.168.100.100 -P 3306
- 基于Socket连接方式(本地)
[root@localhost ~]# mysql -u root -p -S /tmp/mysqld.sock
3.3 MySQL程序运行原理
3.3.1 mysqld程序结构
3.3.2 连接层
(1) 提供连接协议:TPC/IP , SOCKET
(2)提供验证:用户、密码,IP,SOCKET
(3)提供专用连接线程:接受用户SQL,返回结果
3.3.3 SQL层重点
(1)接收上层传送的SQL语句 (2)语法验证模块:验证语句语法 (3)语义检查:判断SQL语句的类型
DDL :数据定义语言
DCL :数据控制语言
DML :数据操作语言
DQL :数据查询语言
......
(4)权限检查:用户对库表有没有权限
(5)解析器:进行SQL的预处理,产生执行计划
(6)优化器:根据解析器得出的多种执行计划,进行判断,选择最优的执行计划
代价模型:资源(CPU IO MEN)的耗损评估性能好坏
(7)执行器:根据最有执行计划,执行SQL语句,产生执行结果
(8)提供查询缓存(默认没有开启),会使用redis tair替代查询缓存功能
(9)提供日志记录:bin-log日志,默认没有开启
3.3.4 存储引擎层(类似于文件系统)
负责根据SQL层执行的结果,从磁盘上拿数据。将16进制的磁盘数据,交由SQL架构化成表,由连接层的专用线程返回给用户。
3.4 逻辑结构
3.4.1 库
库:库名,库权限,库数据类型等
3.4.2 表(二维表)
列:字段
行:记录
# MySQL为了将来数据的准确、规范、有意义,对于传统认知的二维表添加了更多的功能
表属性:权限,存储引擎,字符集
列属性:数据类型、约束、其他属性(默认值,自增长、注释)
3.5 物理结构
3.5.1 库的物理存储结构
用文件系统的目录来存储
3.5.2 表的物理存储结构
MyISM(存储引擎)的表: user.frm:列的相关信息 user.MYD:数据行 user.MYI:索引信息
InnoDB(默认存储引擎)的表: time_zone.frm:存储列相关信息 time_zone.ibd:数据行+索引
3.6 表的段、区、页(16K)
段:一个表就是一个段,包含一个或多个区
区:一个或连续的多个页
页:最小的存储单元
3.7 用户、权限管理
3.7.1 用户
登录、管理数据库
3.7.2 定义用户方法
user1@'192.168.100.%'
user1@'%'
user1@'localhost'
user1@'127.0.0.1'
user1@'db02'
user1@'192.168.10.10%'
管理操作
mysql> create user user1@'192.168.100.100' identified by '123';
# 创建用户并设置密码
mysql> select user,host,authentication_string from mysql.user;
# 查询用户
mysql> alter user user1@'192.168.100.100' identified by '123';
# 修改用户
mysql> drop user user1@'192.168.100.100';
# 删除用户
3.7.3 权限
SELECT,INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN,
PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER,
CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE,
REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE,IALTER
ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE
ALL:以上所有权限,一般是普通管理员拥有 with grant option:超级管理员才具备,给别的用户授权的功能 应用用户:SELECT INSERT UPDATE DELETE(生产中权限使用)
授权语法:
grant 权限 on 对象 to 用户 identified by ‘密码’;
权限对象语法:
*.* # 所有库所有表,适用管理用户
test.* # test库下的所有表,适用开发和应用用户
test.t1 # test库中的t1表
3.7.4 MySQL8.0注意
MySQL8.0都grant添加了新特性,将用户创建与授权独立开。不在支持在用户未创建的时使用grant授权并创建用户
3.7.5 查询权限
mysql> show grants for test@'1921.168.100.100/255.255.255.0';
3.7.6 回收权限
mysql> revoke delete on test.* from user1@‘192.168.100.100/255.255.255.0’;
3.7.7 本地管理员忘记密码
[root@localhost ~]# mysqld_safe --skip-grant-tables --skip-networking &
[root@localhost ~]# mysql -u root -p
mysql> flush privileges;
mysql> alter user root@'localhost' identified by '123';
# 跳过授权表并关闭TCP/IP连接方式,只允许本地登录。进入后修改管理密码
3.8 MySQL启动方式
# 以上多种该方式,都可以单独启动MySQL服务
# mysqld_safe和mysqld一般是在临时维护时使用
# 另外,从centos7系统开始,自持systemd直接调用mysqld的方式进行启动数据库
四、多实例应用
4.1 准备多个目录
[root@localhost ~]# mkdir -p /data/330{7,8,9}/data
4.2 准备配置文件
[root@localhost ~]# cat > /data/3307/my.cnf <<EOF
[mysqld]
basedir=/apps/mysql
datadir=/data/3307/data
socket=/data/3307/mysql.sock
log_error=/data/3307/mysql.log
port=3307
server_id=7
log_bin=/data/3307/mysql-bin.log
EOF
[root@localhost ~]# cat > /data/3308/my.cnf <<EOF
[mysqld]
basedir=/apps/mysql
datadir=/data/3308/data
socket=/data/3308/mysql.sock
log_error=/data/3308/mysql.log
port=3308
server_id=8
log_bin=/data/3308/mysql-bin.log
EOF
[root@localhost ~]# cat > /data/3309/my.cnf <<EOF
[mysqld]
basedir=/apps/mysql
datadir=/data/3309/data
socket=/data/3309/mysql.sock
log_error=/data/3307/mysql.log
port=3309
server_id=9
log_bin=/data/3309/mysql-bin.log
EOF
4.3 初始化数据
[root@localhost system]# mv /etc/my.cnf /etc/my.cnf.bak
# 将原有的配置文件重命名,初始化可能会读取/etc/my.cnf配置文件,初始化完成后可修改回来
[root@localhost mysql]# mysqld --initialize-insecure --user=mysql --basedir=/apps/mysql --datadir=/data/3307/data
[root@localhost mysql]# mysqld --initialize-insecure --user=mysql --basedir=/apps/mysql --datadir=/data/3308/data
[root@localhost mysql]# mysqld --initialize-insecure --user=mysql --basedir=/apps/mysql --datadir=/data/3309/data
[root@localhost system]# mv /etc/my.cnf.bak /etc/my.cnf
4.4 配置管理脚本
[root@localhost ~]# cd /etc/systemd/system/
[root@localhost system]# cp mysqld.service mysqld3307.service
[root@localhost system]# cp mysqld.service mysqld3308.service
[root@localhost system]# cp mysqld.service mysqld3309.service
[root@localhost system]# sed -i 's#ExecStart.*#ExecStart=/apps/mysql/bin/mysqld --defaults-file=/data/3307/my.cnf#g' mysqld3307.service
[root@localhost system]# sed -i 's#ExecStart.*#ExecStart=/apps/mysql/bin/mysqld --defaults-file=/data/3308/my.cnf#g' mysqld3308.service
[root@localhost system]# sed -i 's#ExecStart.*#ExecStart=/apps/mysql/bin/mysqld --defaults-file=/data/3309/my.cnf#g' mysqld3309.service
[root@localhost system]# systemctl daemon-reload
4.5 授权
[root@localhost ~]# chown -R mysql. /data/
4.6 启动数据库
[root@localhost system]# systemctl start mysqld3307
[root@localhost system]# systemctl start mysqld3308
[root@localhost system]# systemctl start mysqld3309
- 多实例验证
[root@localhost system]# netstat -atnup|grep 330
tcp6 0 0 :::3307 :::* LISTEN 2535/mysqld
tcp6 0 0 :::3308 :::* LISTEN 2569/mysqld
tcp6 0 0 :::3309 :::* LISTEN 2603/mysqld
五、SQL基础应用
5.1 SQL语言
结构化查询语言
通过sql_mode来控制
5.2 SQL分类
DDL:数据定义语言
DCL:数据控制语言
DML:数据操作语言
DQL:数据查询语言
5.3 数据类型、表属性、字符集...
5.3.1 数据类型
5.3.1.1 作用
保证数据的准确性和标准性
六、DDL
6.1 库定义
> create database zabbix charset utf8mb4 collate utf8mb4_bin;
# 创建zabbix数据库并定义默认字符集为utf8mb4,定义校对规则为utf8mb4_bin(例如区分大小写类型等校对规则,可不设置此项)
> show databases;
# 查看所有库
> show create database zabbix;
# 查看库的创建语句
> drop database zabbix;
# 删除数据库
> alter database zabbix charset utf8mb4_bin;
# 修改数据库字符集
6.2 表定义
>create table t1(id int UNSIGNED NOT NULL AUTO_INCREMENT ,name varchar(255) NOT NULL ,PRIMARY KEY(`ID`)) ENGINE INNODB CHARSET utf8mb4;
# 创建t1表,并设置字段id为int类型,设置无负符号,非空,自增长,name字段为可变长字符串,非空,主键为ID字段。存储引擎为INNODB,默认表的字符集为utf8mb4。
> show tables;
# 查看所有表
> show create table t1;
# 查看创建表的语句
> create table t2 like t1;
# 创建一个t2表跟t1表一样
> drop table t1;
# 删除表
> desc t1;
# 查看表的字段
> alter table t1 add age int unsigned not null default 0 comment '年龄' alter id;
# 在t1表中添加一列age 类型为整数型 非负 非空 默认值为0 注释为年龄。 指定在id列后插入。如果想在第一列插入则使用first。例子如下
> alter table t1 add age int unsigned not null default 0 comment '年龄' first;
> alter table t1 reanme t3;
# 重命名t1表为t3
> alter table t1 modify age char not null default 99 comment '年龄';
# 修改列属性不修改列名字
> alter table t1 change t4 age varchar(255) not null default 99 comment '年龄';
# 修改列属性同时修改列名称
> alter table t1 drop id;
# 删除指定列
6.2.1 表属性
PRIMARY KEY:主键约束,表中只能有一个PRIMARY KEY,非空且唯一
NOT NULL:非空约束,不能是空值
UNIQUE KEY:唯一键约束,不允许重复值
DEFAULT:一般配合NOT NULL 使用。默认值。
UNSIGNED:无符号。一般和数字列使用。非负数。
COMMENT:注释。
AUTO_INCREMENT:自增长。
建表规范:
- 表名小写,不能数字开头
- 不能是保留字符。在mysql中的关键字符
- 选择合适类型和长度
- 每个列设置DEFAULT和NOT NULL,对于数字用0填充,对于字符串用有效字符填充
- 每个列设置注释
- 表必须设置存储引擎和字符集
- 主键尽量是无关数字列,最好自增长
- EMUN不要用数字,只能是字符串类型
七、DCL
> grant all privileges on *.* to test@'192.168.100.0/255.255.255.0' identified by '123'
# 创建并授权test用户所有库的所有权限从192.168.100.0网段使用123密码登录mysql
八、DML
> insert into t3(name,age) values('zhangsan',12);
# 在t3表中插入一条数据name为’zhangsan‘,age为12的数据行
> insert into t3(name,age) values('zhangsan',12),('lisi',15);
# 插入多行数据
九、DQL
3306 [zabbix]>select @@port;
+--------+
| @@port |
+--------+
| 3306 |
+--------+
1 row in set (0.00 sec)
# 查询一些系统信息,basedir、datadir等
3306 [zabbix]>show variables like '%auth_%';
+-------------------------------+-----------------------+
| Variable_name | Value |
+-------------------------------+-----------------------+
| default_authentication_plugin | mysql_native_password |
+-------------------------------+-----------------------+
1 row in set (0.00 sec)
# 模糊进行查询
3306 [zabbix]>select database();
+------------+
| database() |
+------------+
| zabbix |
+------------+
1 row in set (0.00 sec)
# 查看mysql的函数
重点
3306 [zabbix]>select * from t3 limit 5;
+----------+-----+
| name | age |
+----------+-----+
| zhangsan | 12 |
+----------+-----+
1 row in set (0.00 sec)
# 查看t3表的前5行信息,生产中不要全部查询,数据量太大
3306 [zabbix]>select * from t3 where name='lisi';
+------+-----+
| name | age |
+------+-----+
| lisi | 15 |
+------+-----+
1 row in set (0.00 sec)
# 使用where 进行条件查询 再=判断也可用> < <= >=等数值判断大小
3306 [zabbix]>select * from t3 where name='lisi' and age=15;
+------+-----+
| name | age |
+------+-----+
| lisi | 15 |
+------+-----+
1 row in set (0.00 sec)
# where可以与and和or进行逻辑链接
3306 [zabbix]>select * from t3 where age between 10 and 15;
+----------+-----+
| name | age |
+----------+-----+
| zhangsan | 12 |
| lisi | 15 |
| wangwu | 11 |
+----------+-----+
3 rows in set (0.00 sec)
# 使用between查询两值之间得结果
3306 [zabbix]>select * from t3 where name like 'san%';
+----------+-----+
| name | age |
+----------+-----+
| zhangsan | 12 |
+----------+-----+
1 row in set (0.00 sec)
# 查询t3中name字段数据行中相似san的数据。模糊查询。不要查询前后都加%san%。这样不会走索引,会很影响性能。
3306 [zabbix]>select * from t3 where age in (12,15);
+----------+-----+
| name | age |
+----------+-----+
| zhangsan | 12 |
| lisi | 15 |
+----------+-----+
2 rows in set (0.00 sec)
# 查询age值为12或15的数据。类似于where or 的用法。
9.1 统计
9.1.1 聚合函数
聚合函数:MAX()、MIN()、AVG()、COUNT()、SUM()
GROUP_CONCAT() 分组
DISTINCT 去重复
9.1.2 select语句书写顺序
select from where group by having order by limit
9.1.3 group_by
将某列中有共同条件的数据行,分成一组
3306 [zabbix]>select age,count(name) from t3 group by age;
+-----+-------------+
| age | count(name) |
+-----+-------------+
| 11 | 1 |
| 12 | 3 |
| 15 | 1 |
+-----+-------------+
3 rows in set (0.00 sec)
# 使用group by 对age进行分组,相同年龄的分一组 然后count将分组出来的name进行计数
3306 [zabbix]>select age,group_concat(name) from t3 group by age;
+-----+----------------------+
| age | group_concat(name) |
+-----+----------------------+
| 11 | wangwu |
| 12 | zhangsan,mazi,wanger |
| 15 | lisi |
+-----+----------------------+
3 rows in set (0.00 sec)
# 不以计数显示而直接将内容全部显示
9.1.4 having
3306 [zabbix]>select age,count(name) from t3 group by age having age>=12;
+-----+-------------+
| age | count(name) |
+-----+-------------+
| 12 | 3 |
| 15 | 1 |
+-----+-------------+
2 rows in set (0.00 sec)
# having用于再group by 分组之后对数据再进行判断时使用,where条件不行。where不能用于在group by 之后进行条件判断
9.1.5 order by
3306 [zabbix]>select * from zabbix.t3 order by age;
+----------+-----+
| name | age |
+----------+-----+
| wangwu | 11 |
| zhangsan | 12 |
| mazi | 12 |
| wanger | 12 |
| lisi | 15 |
+----------+-----+
5 rows in set (0.01 sec)
# 查询结果并对age列进行排序,从小到大
3306 [zabbix]>select * from zabbix.t3 order by age desc;
+----------+-----+
| name | age |
+----------+-----+
| lisi | 15 |
| zhangsan | 12 |
| mazi | 12 |
| wanger | 12 |
| wangwu | 11 |
+----------+-----+
5 rows in set (0.00 sec)
# 查询结果并对age列进行排序,从大到小
9.1.6 limit
3306 [zabbix]>select * from zabbix.t3 order by age desc limit 3 ;
+----------+-----+
| name | age |
+----------+-----+
| lisi | 15 |
| zhangsan | 12 |
| mazi | 12 |
+----------+-----+
3 rows in set (0.00 sec)
# 对查询的结果只取前三个
3306 [zabbix]>select * from zabbix.t3 order by age desc limit 3,2 ;
+--------+-----+
| name | age |
+--------+-----+
| wanger | 12 |
| wangwu | 11 |
+--------+-----+
2 rows in set (0.00 sec)
# 对查询的结果取从第3行后的2行,同下面的用法,但是下面的方面会将第3行也显示
3306 [zabbix]>select * from zabbix.t3 order by age desc limit 3 offset 2;
+--------+-----+
| name | age |
+--------+-----+
| mazi | 12 |
| wanger | 12 |
| wangwu | 11 |
+--------+-----+
3 rows in set (0.00 sec)
9.1.7 多表查询
3306 [zabbix]>select t2.id,t3.name,t3.age from t3 join t2 on t2.`name`=t3.`name` where t3.age>=12;
+----+----------+-----+
| id | name | age |
+----+----------+-----+
| 1 | zhangsan | 12 |
| 2 | lisi | 15 |
| 4 | mazi | 12 |
| 5 | wanger | 12 |
+----+----------+-----+
4 rows in set (0.00 sec)
# 查询t2、t3表中有相关信息的数据。join 需要关联的表 on 有关的列。
多张表查询
from a join a.x = b.y on join c b.n = c.m
9.2 元数据获取
元数据存储在“基表”中
通过专门的DDL语句、DCL语句进行修改
information_schema中保存了大量有关元数据的视图
show命令封装好功能,提供一些基础元数据查询
9.2.1 视图
类似于别名。将一条长SQL语句定义一个别名 方便调用
定义方法:
3306 [zabbix]>create view aa as select t2.id,t3.name,t3.age from t3 join t2 on t2.`name`=t3.`name` where t3.age>=12;
Query OK, 0 rows affected (0.01 sec)
3306 [zabbix]>select * from aa;
+----+----------+-----+
| id | name | age |
+----+----------+-----+
| 1 | zhangsan | 12 |
| 2 | lisi | 15 |
| 4 | mazi | 12 |
| 5 | wanger | 12 |
+----+----------+-----+
4 rows in set (0.00 sec)
9.2.2 information_schema
TABLE_SCHEMA :表所在的库名
TABLE_NAME:表名
ENGINE:存储引擎
TABLE_ROWS:数据行数量
AVG_ROW_LENGTH :平均行长度
INDEX_LENGTH:索引长度
3306 [information_schema]>select table_schema,TABLE_NAME from TABLES limit 3;
+--------------------+---------------------------------------+
| table_schema | TABLE_NAME |
+--------------------+---------------------------------------+
| information_schema | CHARACTER_SETS |
| information_schema | COLLATIONS |
| information_schema | COLLATION_CHARACTER_SET_APPLICABILITY |
+--------------------+---------------------------------------+
3 rows in set (0.01 sec)
# 显示所有库的所有表信息,此处取前三行
select table_schema,group_concat(TABLE_NAME),ENGINE from TABLES where engine='INNODB' group by table_schema;
# 显示存储引擎为INNODB的数据库的所有表。效果如下
3306 [information_schema]>select table_schema,(table_rows*avg_row_length+index_length)/1024 from information_schema.TABLES where table_schema='zabbi'
+--------------+-----------------------------------------------+
| table_schema | (table_rows*avg_row_length+index_length)/1024 |
+--------------+-----------------------------------------------+
| zabbix | 16.0000 |
+--------------+-----------------------------------------------+
1 row in set (0.00 sec)
# 统计zabbix库中t1表中数据量大小 算法为表的数据行数*表的平均长度+索引长度
3306 [information_schema]>select table_schema,sum((avg_row_length*table_rows+index_length)/1024) from information_schema.tables group by table_schema order by sum((avg_row_length*table_rows+index_length)/1024) desc;
+--------------------+----------------------------------------------------+
| table_schema | sum((avg_row_length*table_rows+index_length)/1024) |
+--------------------+----------------------------------------------------+
| mysql | 2388.3419 |
| blog | 623.9678 |
| my_college | 63.9912 |
| zabbix | 47.9961 |
| sys | 15.9961 |
| performance_schema | 0.0000 |
| information_schema | NULL |
+--------------------+----------------------------------------------------+
7 rows in set (0.03 sec)
# 统计所有库中所有表的大小并从大到小排列
十、MHA高可用
10.1 环境准备
最低三台mysql节点。
master:192.168.100.104 role:manager node
slave1:192.168.100.103 role:node
slave2:192.168.100.102 role:node
三台都配置好主从关系
10.2 配置无交互登录
# 每个节点都生成并分发。如果再测试中manager节点在master或者slave上,manager节点需要对本身节点也分发公钥信息,否则后面用mha自带脚本呢测试ssh会报错
[root@localhost mysql]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:OP291AenHhIzufvaPGlhmgcSD6Xw49KL450LP+MVYHA [email protected]
The key's randomart image is:
+---[RSA 2048]----+
| . E |
| .o . |
| ooo |
| o .*. . |
| o So =* . .|
| ...+.oBo+ |
| .o.o*=+o.|
| o+++oB=o |
| ..o*++==. |
+----[SHA256]-----+
# 每台分发公钥信息
[root@localhost ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.100.103 (192.168.100.103)' can't be established.
ECDSA key fingerprint is SHA256:LCLBXYO1AIeD+kWYwRzv1DqcZnBVG9YMGgn02HOeOXo.
ECDSA key fingerprint is MD5:76:3d:54:97:0c:40:c1:1a:75:4a:d4:82:a0:64:a8:13.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.
# 测试登录
[root@localhost ~]# ssh [email protected]
Last login: Sun May 16 12:14:00 2021 from 192.168.100.253
[root@localhost ~]#
10.3 配置mysql为半同步复制
为了尽可能的减少主库硬件损坏宕机造成的数据丢失,因此在配置MHA的同时建议配置成MySQL的半同步复制。
注:mysql半同步插件是由谷歌提供,具体位置/usr/local/mysql/lib/plugin/下,一个是master用的semisync_master.so,一个是slave用的semisync_slave.so。
如果不清楚Plugin的目录,用如下命令查找:
3306 [(none)]>show variables like '%plugin_dir%';
+---------------+-------------------------+
| Variable_name | Value |
+---------------+-------------------------+
| plugin_dir | /apps/mysql/lib/plugin/ |
+---------------+-------------------------+
1 row in set (0.00 sec)
10.3.1 主节点插件安装
在MySQL上安装插件需要数据库支持动态载入,检查是否支持,用如下命令检测:
3306 [(none)]>show variables like '%have_dynamic%';
+----------------------+-------+
| Variable_name | Value |
+----------------------+-------+
| have_dynamic_loading | YES |
+----------------------+-------+
1 row in set (0.00 sec)
# yes则为可以
安装插件,其他mysql节点相同操作
3306 [(none)]>install plugin rpl_semi_sync_master soname 'semisync_master.so';
Query OK, 0 rows affected (0.02 sec)
3306 [(none)]>install plugin rpl_semi_sync_slave soname 'semisync_slave.so';
Query OK, 0 rows affected (0.01 sec)
10.3.2 查看插件安装
3306 [(none)]>show plugins;
10.3.3 查看半同步信息
3306 [(none)]>show variables like '%rpl_semi_sync%';
+-------------------------------------------+------------+
| Variable_name | Value |
+-------------------------------------------+------------+
| rpl_semi_sync_master_enabled | OFF |
| rpl_semi_sync_master_timeout | 10000 |
| rpl_semi_sync_master_trace_level | 32 |
| rpl_semi_sync_master_wait_for_slave_count | 1 |
| rpl_semi_sync_master_wait_no_slave | ON |
| rpl_semi_sync_master_wait_point | AFTER_SYNC |
| rpl_semi_sync_slave_enabled | OFF |
| rpl_semi_sync_slave_trace_level | 32 |
+-------------------------------------------+------------+
8 rows in set (0.00 sec)
上面只是安装的查看,并没有启动
10.3.4 配置my.cnf
注:若主MYSQL服务器已经存在,只是后期才搭建从MYSQL服务器,在置配数据同步前应先将主 MYSQL服务器的要同步的数据库拷贝到从MYSQL服务器上(如先在主MYSQL上备份数据库,再用备份 在从MYSQL服务器上恢复)
- matser节点
[root@localhost ~]# vim /etc/my.cnf
[mysqld]
user=mysql
basedir=/apps/mysql
datadir=/data/mysql
log-bin=/data/mysql/mysql-bin.log
server_id=6
port=3306
socket=/apps/mysql/mysql.sock
symbolic_links=0
binlog_format=mixed
# 设置binlog日志记录模式
rpl_semi_sync_master_enabled=1
# 开启半同步
rpl_semi_sync_master_timeout=1000
# 设置主服务器等待确认消息10秒后,不在等待,变为异步方式
rpl_semi_sync_slave_enabled=1
# 开启从库半同步
relay_log_purge=0
# 设置relay_log是否自动情况不再需要中继日志。默认值为1。禁止 SQL 线程在执行完一个 relay log 后自动将其删除,对于MHA场景下,对
于某些滞后从库的恢复依赖于其他从库的relay log,因此采取禁用自动删除功能
#relay_log=/data/mysql/relay-bin
# 设置relay_log的位置和名称
[mysql]
socket=/apps/mysql/mysql.sock
prompt=3306 [\\d]>
[root@localhost ~]# service mysqld restart
# 重启数据库
- slave节点配置
[root@localhost ~]# vim /etc/my.cnf
[mysqld]
user=mysql
basedir=/apps/mysql
datadir=/data/mysql
server_id=3
port=3306
socket=/apps/mysql/mysql.sock
symbolic_links=0
log-bin=/data/mysql/mysql-bin.log
rpl_semi_sync_master_enabled=1
rpl_semi_sync_master_timeout=1000
rpl_semi_sync_slave_enabled=1
binlog_format=mixed
rpl_semi_sync_slave_enabled=1
relay_log_purge=0
#relay_log=/data/mysql/relay-bin
[mysql]
socket=/apps/mysql/mysql.sock
prompt=3306 [\\d]>
[root@localhost ~]# service mysqld restart
# 重启数据库
- 登录查看状态
3306 [(none)]>show variables like '%rpl_semi_sync%';
+-------------------------------------------+------------+
| Variable_name | Value |
+-------------------------------------------+------------+
| rpl_semi_sync_master_enabled | ON |
| rpl_semi_sync_master_timeout | 1000 |
| rpl_semi_sync_master_trace_level | 32 |
| rpl_semi_sync_master_wait_for_slave_count | 1 |
| rpl_semi_sync_master_wait_no_slave | ON |
| rpl_semi_sync_master_wait_point | AFTER_SYNC |
| rpl_semi_sync_slave_enabled | ON |
| rpl_semi_sync_slave_trace_level | 32 |
+-------------------------------------------+------------+
3306 [(none)]> show status like '%rpl_semi_sync%';
+--------------------------------------------+-------+
| Variable_name | Value |
+--------------------------------------------+-------+
| Rpl_semi_sync_master_clients | 0 |
| Rpl_semi_sync_master_net_avg_wait_time | 0 |
| Rpl_semi_sync_master_net_wait_time | 0 |
| Rpl_semi_sync_master_net_waits | 0 |
| Rpl_semi_sync_master_no_times | 0 |
| Rpl_semi_sync_master_no_tx | 0 |
| Rpl_semi_sync_master_status | ON |
| Rpl_semi_sync_master_timefunc_failures | 0 |
| Rpl_semi_sync_master_tx_avg_wait_time | 0 |
| Rpl_semi_sync_master_tx_wait_time | 0 |
| Rpl_semi_sync_master_tx_waits | 0 |
| Rpl_semi_sync_master_wait_pos_backtraverse | 0 |
| Rpl_semi_sync_master_wait_sessions | 0 |
| Rpl_semi_sync_master_yes_tx | 0 |
| Rpl_semi_sync_slave_status | OFF |
+--------------------------------------------+-------+
15 rows in set (0.00 sec)
# 参数注意
rpl_semi_sync_master_status :显示主服务是异步复制模式还是半同步复制模式
rpl_semi_sync_master_clients :显示有多少个从服务器配置为半同步复制模式
rpl_semi_sync_master_yes_tx :显示从服务器确认成功提交的数量
rpl_semi_sync_master_no_tx :显示从服务器确认不成功提交的数量
rpl_semi_sync_master_tx_avg_wait_time :事务因开启 semi_sync ,平均需要额外等待的时间
rpl_semi_sync_master_net_avg_wait_time :事务进入等待队列后,到网络平均等待时间
10.4 配置mysql-mha
mha包括manager节点和node节点
node节点:包括原有的MySQL复制结构中的主机,至少3台,即1主2从,当masterfailover后,还能保证主从结构;只需安装node包。
manager节点:运行监控脚本,负责monitoring 和 auto-failover;需要安装node包和manager包。
10.4.1 依赖解决
[root@localhost ~]# yum -y install perl-DBD-MySQL perl-Config-Tiny perl-Log-Dispatch perl-Parallel-ForkManager perl-Config-IniFiles ncftp perl-Params-Validate perl-CPAN perl-Test-Mock-LWP.noarch perl-LWP-Authen-Negotiate.noarch perl-devel perl-ExtUtils-CBuilder perl-ExtUtils-MakeMaker
# 如果是源码包则安装以上依赖,如果是rpm包,安装以下
[root@localhost ~]# yum -y install perl-DBD-MySQL
10.4.2 node端安装
node节点和manager节点都需要安装node端
[root@localhost ~]# yum -y install mha4mysql-node-0.58-0.el7.centos.noarch.rpm
10.4.3 manager端安装
[root@localhost ~]# yum -y install mha4mysql-manager-0.58-0.el7.centos.noarch.rpm
10.4.4 编辑mha配置文件
[root@localhost ~]# vim /etc/masterha/app1.conf
[server default]
manager_workdir=/masterha/app1
manager_log=/masterha/app1/manager.log
user=manager
password=123456
ssh_user=root
repl_user=slave
repl_password=123
ping_interval=1
[server1]
hostname=192.168.100.104
port=3306
master_binlog_dir=/data/mysql
candidate_master=1
[server2]
hostname=192.168.100.103
port=3306
master_binlog_dir=/data/mysql
candidate_master=1
[server3]
hostname=192.168.100.101
port=3306
master_binlog_dir=/data/mysql
no_master=1
10.4.5 测试ssh
[root@localhost ~]# masterha_check_ssh --conf=/etc/masterha/app1.conf
Sun May 16 22:56:39 2021 - [info] Reading default configuration from /etc/masterha_default.cnf..
Sun May 16 22:56:39 2021 - [info] Reading application default configuration from /etc/masterha/app1.conf..
Sun May 16 22:56:39 2021 - [info] Reading server configuration from /etc/masterha/app1.conf..
Sun May 16 22:56:39 2021 - [info] Starting SSH connection tests..
Sun May 16 22:56:41 2021 - [debug]
Sun May 16 22:56:40 2021 - [debug] Connecting via SSH from [email protected](192.168.100.103:22) to [email protected](192.168.100.104:22)..
Sun May 16 22:56:40 2021 - [debug] ok.
Sun May 16 22:56:40 2021 - [debug] Connecting via SSH from [email protected](192.168.100.103:22) to [email protected](192.168.100.101:22)..
Sun May 16 22:56:40 2021 - [debug] ok.
Sun May 16 22:56:42 2021 - [debug]
Sun May 16 22:56:40 2021 - [debug] Connecting via SSH from [email protected](192.168.100.101:22) to [email protected](192.168.100.104:22)..
Sun May 16 22:56:41 2021 - [debug] ok.
Sun May 16 22:56:41 2021 - [debug] Connecting via SSH from [email protected](192.168.100.101:22) to [email protected](192.168.100.103:22)..
Sun May 16 22:56:41 2021 - [debug] ok.
Sun May 16 22:56:46 2021 - [debug]
Sun May 16 22:56:39 2021 - [debug] Connecting via SSH from [email protected](192.168.100.104:22) to [email protected](192.168.100.103:22)..
Sun May 16 22:56:45 2021 - [debug] ok.
Sun May 16 22:56:45 2021 - [debug] Connecting via SSH from [email protected](192.168.100.104:22) to [email protected](192.168.100.101:22)..
Sun May 16 22:56:45 2021 - [debug] ok.
Sun May 16 22:56:46 2021 - [info] All SSH connection tests passed successfully.
10.4.6 测试集群复制有效性
[root@localhost ~]# masterha_check_repl --conf=/etc/masterha/app1.conf
......
Sun May 16 22:57:58 2021 - [info] Checking replication health on 192.168.100.103..
Sun May 16 22:57:58 2021 - [info] ok.
Sun May 16 22:57:58 2021 - [info] Checking replication health on 192.168.100.101..
Sun May 16 22:57:58 2021 - [info] ok.
Sun May 16 22:57:58 2021 - [warning] master_ip_failover_script is not defined.
Sun May 16 22:57:58 2021 - [warning] shutdown_script is not defined.
Sun May 16 22:57:58 2021 - [info] Got exit code 0 (Not master dead).
MySQL Replication Health is OK.
# 在这需要注意,虽然在profile中声明了PATH变量的mysql,但是mha脚本中无法识别,mysqlbinlog以及mysql命令 需要以下命令软连接
[root@localhost ~]# ln -s /apps/mysql/bin/mysqlbinlog /usr/bin
[root@localhost ~]# ln -s /apps/mysql/bin/mysql /usr/bin
10.4.7 启动manager
[root@localhost ~]# nohup masterha_manager --conf=/etc/masterha/app1.conf & >/tmp/mha-manager.log
查看状态
[root@localhost ~]# masterha_check_status --conf=/etc/masterha/app1.conf
app1 (pid:102002) is running(0:PING_OK), master:192.168.100.104
10.5 故障演练
manager端
[root@localhost ~]# tailf /masterha/app1/manager.log
# 查看变化过程
将现主库停掉
[root@localhost ~]# service mysqld stop
发现上面manager.log发生变化
Started automated(non-interactive) failover.
The latest slave 192.168.100.103(192.168.100.103:3306) has all relay logs for recovery.
Selected 192.168.100.103(192.168.100.103:3306) as a new master.
192.168.100.103(192.168.100.103:3306): OK: Applying all logs succeeded.
192.168.100.101(192.168.100.101:3306): This host has the latest relay log events.
Generating relay diff files from the latest slave succeeded.
192.168.100.101(192.168.100.101:3306): OK: Applying all logs succeeded. Slave started, replicating from 192.168.100.103(192.168.100.103:3306)
192.168.100.103(192.168.100.103:3306): Resetting slave info succeeded.
Master failover to 192.168.100.103(192.168.100.103:3306) completed successfully.
从库192.168.100.101进行查看
3306 [(none)]>show slave status\G;
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.100.103
Master_User: slave1
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000004
# 发现主库已经切换为192.168.100.103
十一、MHA日常管理操作
11.1 检查以下文件
发生主从切换后,MHAmanager服务会自动停掉,且在manager_workdir(/masterha/app1)目录下面生成文件app1.failover.complete。
[root@localhost ~]# ll /masterha/app1/
总用量 24
-rw-r--r-- 1 root root 0 5月 16 23:08 app1.failover.complete
-rw-r--r-- 1 root root 22250 5月 16 23:08 manager.log
若要启动MHA,必须先确保无此文件, 如果有这个提示,那么删除此文件。
11.2 slave宕掉
当有slave 节点宕掉时,默认是启动不了的,加上 --ignore_fail_on_start 即使有节点宕掉也能启动MHA,如下:
[root@localhost ~]# nohup masterha_manager --conf=/etc/masterha/app1.cnf --ignore_fail_on_start & >/tmp/mha_manager.log &
11.3 主从切换后操作
方案一是将原主库变成从库
方案二
十二、VIP实现
脚本文件,但是需要先在主配置文件中添加脚本执行
[root@localhost ~]# vim /etc/masterha/app1.conf
master_ip_failover_script=/etc/masterha/master_ip_failover
master_ip_online_change_script=/etc/masterha/master_ip_online_change
[root@localhost ~]# vim /etc/masterha/master_ip_failover
#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';
use Getopt::Long;
my (
$command, $ssh_user, $orig_master_host, $orig_master_ip,
$orig_master_port, $new_master_host, $new_master_ip, $new_master_port
);
my $gateway = '192.168.11.1'; ---这个是网关地址
my $vip = '192.168.11.251/24'; ---vip地址
my $onlyvip = '192.168.11.251'; vip
my $key = '0'; ---网卡的别名编号
my $eth = 'ens32'; --网卡名称
my $ssh_start_vip = "/sbin/ifconfig $eth:$key $vip up;/sbin/arping -I $eth -c 3 -s $onlyvip $gateway";
my $ssh_stop_vip = "/sbin/ifconfig $eth:$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,
);
exit &main();
sub main {
print "\n\nIN SCRIPT TEST====$ssh_stop_vip==$ssh_start_vip===\n\n";
print "\n\nIN Master_ip_failover_command:====$command===\n\n";
if ( $command eq "stop" || $command eq "stopssh" ) {
my $exit_code = 1;
eval {
print "Disabling the VIP on old master: $orig_master_host \n";
&stop_vip();
$exit_code = 0;
};
if ($@) {
warn "Got Error: $@\n";
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "start" ) {
my $exit_code = 10;
eval {
print "Enabling the VIP - $vip on the new master - $new_master_host \n";
&start_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";
exit 0;
}
else {
&usage();
exit 1;
}
}
sub start_vip() {
`ssh $ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
sub stop_vip() {
return 0 unless ($ssh_user);
`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";
[root@localhost ~]# vim /etc/masterha/master_ip_online_change
#!/usr/bin/env perl
use strict;
use warnings FATAL =>'all';
use Getopt::Long;
my $vip = '192.168.100.200/24';
my $key = "1";
my $ssh_start_vip = "/sbin/ifconfig ens33:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig ens33:$key down";
my $exit_code = 0;
my (
$command, $orig_master_is_new_slave, $orig_master_host,
$orig_master_ip, $orig_master_port, $orig_master_user,
$orig_master_password, $orig_master_ssh_user, $new_master_host,
$new_master_ip, $new_master_port, $new_master_user,
$new_master_password, $new_master_ssh_user,
);
GetOptions(
'command=s' => \$command,
'orig_master_is_new_slave' => \$orig_master_is_new_slave,
'orig_master_host=s' => \$orig_master_host,
'orig_master_ip=s' => \$orig_master_ip,
'orig_master_port=i' => \$orig_master_port,
'orig_master_user=s' => \$orig_master_user,
'orig_master_password=s' => \$orig_master_password,
'orig_master_ssh_user=s' => \$orig_master_ssh_user,
'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,
'new_master_ssh_user=s' => \$new_master_ssh_user,
);
exit &main();
sub main {
#print "\n\nIN SCRIPT TEST====$ssh_stop_vip==$ssh_start_vip===\n\n";
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 {
print "\n\n\n***************************************************************\n";
print "Disabling the VIP - $vip on old master: $orig_master_host\n";
print "***************************************************************\n\n\n\n";
&stop_vip();
$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 "\n\n\n***************************************************************\n";
print "Enabling the VIP - $vip on new master: $new_master_host \n";
print "***************************************************************\n\n\n\n";
&start_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 $orig_master_ssh_user\@$orig_master_host \" $ssh_start_vip \"`;
exit 0;
}
else {
&usage();
exit 1;
}
}
# A simple system call that enable the VIP on the new master
sub start_vip() {
`ssh $new_master_ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old_master
sub stop_vip() {
`ssh $orig_master_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=po
rt –new_master_host=host –new_master_ip=ip –new_master_port=port\n";
}
然后在现在主业务的节点上开启VIP
[root@localhost ~]# ifconfig ens33:1 192.168.100.200/24
然后测试故障即可
十三、MySQL备份恢复
13.1 xtrabackup
[root@localhost ~]# yum -y install https://downloads.percona.com/downloads/Percona-XtraBackup-2.4/Percona-XtraBackup-2.4.24/binary/redhat/7/x86_64/percona-xtrabackup-24-2.4.24-1.el7.x86_64.rpm
13.1.1 备份方式
物理备份-类似于直接cp-a mysql 的数据目录下文件
(1)对于非Innodb表(比如 myisam)是,锁表cp数据文件,属于一种温备份。
(2)对于Innodb的表(支持事务的),不锁表,拷贝数据页,最终以数据文件的方式保存下来,把一部分redo和undo一并备走,属于热备方式。
13.1.2备份过程恢复过程
0、xbk备份执行的瞬间,立即触发ckpt,已提交的数据脏页,从内存刷写到磁盘,并记录此时的LSN号
1、备份时,拷贝磁盘数据页,并且记录备份过程中产生的redo和undo一起拷贝走,也就是checkpoint LSN之后的日志
2、在恢复之前,模拟Innodb“自动故障恢复”的过程,将redo(前滚)与undo(回滚)进行应用
3、恢复过程是cp 备份到原来数据目录下
13.1.3 xtrabackup使用
13.1.3.1 全备
[root@localhost ~]# innobackupex --user=root --password=123456 /data/backup
xtrabackup: recognized server arguments: --datadir=/data/mysql --server-id=6 --log_bin=/apps/mysql/mysql-bin.log
xtrabackup: recognized client arguments:
220304 05:27:01 innobackupex: Starting the backup operation
IMPORTANT: Please check that the backup run completes successfully.
。。。。。。。
。。。。。。。
。。。。。。。
220304 05:27:03 [00] Copying ib_buffer_pool to /data/backup/2022-03-04_05-27-01/ib_buffer_pool
220304 05:27:03 [00] ...done
220304 05:27:03 Backup created in directory '/data/backup/2022-03-04_05-27-01/'
MySQL binlog position: filename 'mysql-bin.000009', position '154'
220304 05:27:03 [00] Writing /data/backup/2022-03-04_05-27-01/backup-my.cnf
220304 05:27:03 [00] ...done
220304 05:27:03 [00] Writing /data/backup/2022-03-04_05-27-01/xtrabackup_info
220304 05:27:03 [00] ...done
xtrabackup: Transaction log of lsn (6294687) to (6294696) was copied.
220304 05:27:03 completed OK!
[root@localhost backup]# ls
2022-03-04_05-27-01
13.1.3.2 自主定制备份路径
默认备份完成后在目录下生成以时间到时分秒的目录,在日常工作中不需要时分秒可以用以下命令自定义目录名字
[root@localhost backup]# innobackupex --user=root --password=123456 --no-timestamp /data/backup/full
#生成的备份目录名称为full
[root@localhost backup]# ls /data/backup/full/
backup-my.cnf ibdata1 performance_schema wordpress xtrabackup_checkpoints xtrabackup_logfile
ib_buffer_pool mysql sys xtrabackup_binlog_info xtrabackup_info
13.1.3.3 备份多出文件详解
xtrabackup_binlog_info:备份时刻的bin-log日志位置
[root@localhost full]# cat xtrabackup_binlog_info
mysql-bin.000009 154
xtrabackup_checkpoints:
[root@localhost full]# cat xtrabackup_checkpoints
backup_type = full-backuped #备份类型
from_lsn = 0 #上次所到达的LSN号(对于全备就是从0开始,对于增量有别的显示方法)
to_lsn = 6294687 #备份开始时间(ckpt)点数据页的LSN
last_lsn = 6294696 #备份结束后,redo日志最终的LSN
compact = 0
recover_binlog_info = 0
flushed_lsn = 6294696
xtrabackup_info:
xtrabackup_logfile:
13.1.3.2 全备恢复
xtrabackup默认的恢复方式为mysql 的目录下必须是空目录 也就是mysql完全奔溃下然后将mysql的data目录下数据删除的情况,一般不使用自带的恢复。
[root@localhost mysql]# innobackupex --apply-log /data/backup/2022-03-04_05-27-01/
# mysql的redu和undo的回滚恢复
[root@localhost mysql]# innobackupex --copy-back /data/backup/2022-03-04_05-27-01/
#mysql的数据恢复,不需要mysql在启动状态
13.1.3.3 全备恢复踩坑
在使用上面的全备进行恢复时由于使用的是root账户操作,恢复的文件权限也是root,而mysql的运行用户为mysql导致在恢复后启动时innodb 的ibdata1文件不可读,需要将文件权限进行修改
[root@localhost ~]# chown -R mysql. /data/mysql
13.1.3.4 增量备份
此次为实验先将mysql 的biblog进行一次清除方便实验查看reset master
然后创建库和表,并插入一些数据。
退出数据库进行一次全备
[root@localhost mysql]# innobackupex --user=root --password=123456 --no-timestamp /data/backup/`date +%F` &>/tmp/`date +%F`-xbk.log
进行一次数据变化
进行增量备份
[root@localhost mysql]# innobackupex --user=root --password=123456 --no-timestamp --incremental /data/backup/`date +%F`_inc --incremental-basedir=/data/backup/2022-03-04/2 &>/tmp/inc.log
# 备份完成后每天检查此日志文件内容中是否备份完成以及备份目录文件是否完整,还有以下文件检查
[root@localhost mysql]# cat /data/backup/2022-03-04_inc/xtrabackup_checkpoints
backup_type = incremental
from_lsn = 6301147
to_lsn = 6307033
last_lsn = 6307042
compact = 0
recover_binlog_info = 0
flushed_lsn = 6307042
13.1.3.5 增量备份恢复
注意事项:1.增量备份不能单独恢复
2.增量备份必须按照顺序进行合并到全备中
3.所有备份都要apply-log进行整理备份
4.部分备份只要redo不要undo(--redo-only)
[root@localhost mysql]# innobackupex --user=root --password=123456 --apply-log --redo-only /data/backup/2022-03-04/
# 进行第一次的全备apply-log恢复 除了最后一次的增量备份不需要加redu-only,其他都要加上此参数
进行增量备份apply-log恢复并且合并到全备中
[root@localhost mysql]# innobackupex --apply-log --redo-only --incremental-dir=/data/backup/2022-03-04_inc/ /data/backup/2022-03-04/
此操作将增量inc的第一次增量备份apply-log并且合并搭到了全备中
可以查看全备和增量备份的xtrabackup_checkpoints文件中的last_lsn值是否一致,一致则恢复成功,反之不成功。
[root@localhost mysql]# cat /data/backup/2022-03-04/2022-03-04_06-31-41/xtrabackup_checkpoints
backup_type = log-applied
from_lsn = 0
to_lsn = 6307033
last_lsn = 6307042
compact = 0
recover_binlog_info = 0
flushed_lsn = 6307042
[root@localhost mysql]# cat /data/backup/2022-03-04_inc/xtrabackup_checkpoints
backup_type = incremental
from_lsn = 6301147
to_lsn = 6307033
last_lsn = 6307042
compact = 0
recover_binlog_info = 0
flushed_lsn = 6307042
[root@localhost mysql]# innobackupex --apply-log --incremental-dir=/data/backup/2022-03-04_inc2/ /data/backup/2022-03-04/
#最后一次的增量备份不需要加redo-only
[root@localhost mysql]# innobackupex --apply-log /data/backup/2022-03-04/
#最后执行恢复前在执行一次apply-log的回滚操作
[root@localhost mysql]# innobackupex --copy-back /data/backup/2022-03-04/
# 最后将全备进行恢复
当前一天的增量备份恢复后,当天进行的数据还未进行增量备份时数据丢失 需要使用bin-log日志进行恢复,恢复所需要参数在最后一次增量备份的xtrabackup_binlog_info文件中有记录。
[root@localhost mysql]# mysqlbinlog --start-position=219 --stop-position=1176 /apps/mysql/mysql-bin.000001 >/tmp/bin.sql
[root@localhost mysql]# mysql -u root -p
3306 [(none)]>set sql_log_bin=0;
3306 [(none)]>source /tmp/bin.sql;