linuxsystem./云计算加强基础.md
2025-06-19 10:05:48 +08:00

177 KiB
Raw Blame History

linux云计算基础

centos官网www.centos.org

linux发行版本 centos redhat ubuntu debian

一.linux系统安装

物理服务器

vmware workstation 创建一台虚拟机==物理服务器 在虚拟机上安装系统

云服务器:系统不需要单独安装,获取到云服务器后,系统是已经安装好的

1、创建虚拟机

cpu 处理器 men内存 disk磁盘 都是可以变化的 网络采用默认模式(桥接 网络地址转换 仅主机)

2给虚拟机分配镜像

3安装操作系统

时区: Asia/Shanghai

安装方式:最小化安装

图形化安装

磁盘分区:

磁盘20G

windowC盘 系统盘

linux分区 / 根分区 /boot swap

根据实际需求可以进行磁盘的分区

方案 /boot 500m (bioboot 500m)

网络主机名:

开启网络

主机名(不修改使用默认)自定义

root password 所设定的密码是root的密码

root用户是系统自带的具有最高权限 linux系统的超级管理用户

2、服务器

1物理服务器安装操作系统的流程

1 rufus 制作 centos 启动盘

制作u盘 多台机器使用PXE

2 设置启动项 由硬盘启动设置为u盘启动 install centos 跟虚拟机安装一模一样

如果100台服务器需要将100台物理服务器安装centos的操作系统

网络装机 利用PXE进行网络批量装机 PXE自动运维工具 进行批量化的操作系统安装

2单用户模式

一分钟重启

重启后内核按e

找到UTF-8后加上 init=/bin/bash

ctrl+x

mount -o remount,rw /

touch /.autorelabel(如果出现selinux默认开启了无法输入密码需要打这条命令) (都关闭后不要写)

crontab -e 删除计划任务

exec /sbin/init 重启

破解root密码

1.开机

2.按e

3.在UTF-8后面输入一下参数打开一个终端进入救援模式/单用户模式rd.break console==tty0

4.以读写重新挂载临时根目录 mount -o rw,remount /sysroot

5.切换到临时目录 chroot /sysroot

6.修改密码,这里不需要知道之前的密码,重新设定即可 passwd

7.关闭linux自带的安全机制 vi /etc/sysconfig/selinux SELINUX=disabled

8.在根目录下创建隐藏文件autorelable touch /.autorelable

9.exit 退出 reboot 重启

第二种

   	破解root密码
	重启后在内核界面按e
	UTF-8后面输入     init=/bin/bash
	ctrl+x								#重启
	mount  -o remount,rw  /
	touch /.autorelabel					#仅在selinux未关闭时使用
	passwd  root
	exec /sbin/init

3Linux启动级别

0 停机 init 0 == shutdown now

1 单用户模式,用于系统维护

2 多用户模式但不启动NFS

3 完整的多用户模式,带有显示登录 init 3图形切换终端界面

4 预留,未使用

5 图形化界面 init 5

6 重新启动 init 6

4物理设备

IDC数据中心 服务器 网络设备(路由器+交换机+防火墙)网线 机柜 空调

服务器分类: cpu、mem内存、主板、硬盘、网卡接口 vga接口、HDMI接口、use接口、管理接口

机架式服务器

塔式服务器

刀片式服务器

5云产品

云服务器、云存储、云安全

云分类:公有云:华为云 阿里云 腾讯云

私有云

混合云

容器云

3、参数的使用

1ls参数使用

ls -l :显示文件的详细信息 文件类型/权限、硬链接个数、所有者、所属 组、大小、修改时间、名字 或者 ll

ls -lh :以单位显示

ls -i 显示文件的inode号

ls -a :显示隐藏文件

4、date时间

date:查看时间和日期、修改时间和日期

获取当前日期date +%F F日期

获取当前时间date +%H:%M:%S H时 M分 S

获取周几: date +%w w

获取日期+时间 date +%F-%T

touch date +%F 创建当前时间的文件

date -s 3:00 //指定时间

5、Linux目录结构

which获取命令对应的二进制文件存放位置

bin命令文件 二进制文件 程序文件(普通用户)

sbin命令文件 二进制文件 程序文件(管理员用户)

root默认存放root用户的家目录 ~/当前用户家目录

home默认存放普通用户的家目录

var默认存放有变化的文件、比如日志

mnt默认挂载

dev默认存放设备文件

proc虚拟文件

etc默认存放配置文件的目录

tmp临时文件

6、linux文件管理

1路径

绝对路径:以根开始的路径我们称之为绝对路径 

相对路径:从当前目录开始的路径称之为相对路径

2Linux文件类型

— 普通文件 (文本文件,二进制文件,压缩文件,电影,图片)

d 目录文件 (蓝色)

b 设备文件块设备存储设备硬盘U盘/dev/sda,/dev/sda1

c 设备文件(字符设备)打印机,终端,/dev/tty1,/dev/zero

s 套接字文件

p 管道文件

l 链接文件(深蓝色)

3vi编辑器

编辑模式使用i键进入编辑模式可以修改

命令模式:默认进入命令模式,该模式可以看到文件内容,不能编辑

可视模式:第一列注释 ctrl + v I # Esc两下

尾行命令模式wq!

G光标移动到最后一行

gg光标到行首

dd删除光标所在行

dG删除光标的下面的行

u撤销

yy复制

p粘贴

D删除光标后的内容

vi编辑器查找替换

语法格式行s/替换的内容/替换成谁/

查找 在命令模式下输入“/”进入行尾命令模式 要查找的内容 /root n从上往下查看 N从下往上查看

替换:%s/root/ROOT/ 从首行到最后一行替换,只能替换每一行第一个匹配到的

%s/root/ROOT/g 从首行到最后一行,只要匹配到全部替换

510s/.*/#&/ 5行到10行每一行开头加一个#

49s/^#// 4行到9行每行开头的#删除

临时查看和取消行号

: set nu

:set nonu

:set list 查看空格

:set ic 不区分大小写

永久设定行号

/etc/vimrc里面加 set nu

总结使用vim编辑文件的过程中不用鼠标使用键盘键盘上的所有键都是vim、vi快捷键当使用vim/vi打开一个文件时。默认进入命令模式该模式可以看到文件中的内容不能编辑使用快捷键i进入到编辑/插入模式就连可以对文件进行编辑和修改使用上下左右键来查看文件的内容文件编辑或修改完成后需要使用Esc退出编辑模式使用英文冒号进到尾行命令模式然后输入wq保存退出

ctrl+v shift+i 第一行可以注释

4查看命令

cat 参数-n显示行号文件名

head 指定行数 从前往后 默认看前10行

tail 指定行数 从后往前 默认看后10行

tail -f 实时的查看

more less 翻页查看

非正常关闭,再次编辑文件以.swp结尾的隐藏文件

解决方案Q退出 然后删除.swp结尾的

5help手册和man手册

man手册分类

  • 一般命令 8类可以获取命令的使用方法

  • 系统调用库 可以获取配置文件的使用方法或相关信息

  • c标准库

  • 设备文件

  • 配置文件

  • 游戏相关

  • 杂项 //所谓杂项其大部分都是没办法很好分给其他8类帮助

  • 系统管理相关命令

    help手册

    对于每一个命令来讲:语法格式

    [ ] 表示可选项,则需要则用,不需要不用

    { } 表示必选项,即里面的选项为必用

    | 或者的意思 比如a|b的意思就是只能选其中一个

7、用户和组

特性:多用户多任务 多个用户在同一个系统中同一时间执行的不同的任务,他们互相不影响

权限管理机制:每个用户拥有自己的权限

默认的自带的超级管理用户root

使用普通用户对系统进行管理

用户分类centos

超级管理员用户 root 标识 UID 0

系统用户 标识 UID 1-999 包含14和999 0<UID<999

普通用户 标识 UID UID>=1000

使用命令 32 位数字随机密码生成。

< /dev/urandom tr -dc a-z|head -c ${1:-32} ; echo

生成10个大写字母 < /dev/urandom tr -dc A-Z|head -c ${1:-10};echo

生成10个数字 < /dev/urandom tr -dc 0-9|head -c ${1:-10};echo

生成10个数字和大写字母的组合字符串 < /dev/urandom tr -dc 0-9-A-Z|head -c ${1:-10};echo

1 用户

增加用户

useradd 用户名字 创建用户

passwd 用户名字 给用户设置密码

su - 用户名字 切换用户

useradd -u 1000 用户名字 指定用户uid

useradd -d 用户名字 /opt/xiaoshun 指定用户家目录

useradd -s /bin/sh 用户名字 指定登录shell

useradd -r 用户名称 创建系统用户

id -un 获取当前正在使用用户的用户名

创建用户并使用非交互的方式设置该用户的密码为123 echo ' 123 ' | passwd --stdin 用户名

修改用户

usermod -s /sbin/nologin 用户名 禁止用户登录

usermod -u 用户名 1000 修改已创用户uid

usermod -l 新的用户名 旧的用户名 修改用户名

usermod -L 用户名 锁定密码

usermod -U 用户名 解开密码

usermod -G 用户2 用户1 用户1加入到用户2组里用户1有两个组给用户附加组

usermod -aG 组名 用户名 用户附加组 修改用户属组

userdel -r 用户 删除用户

添加用户发生变化的文件

/var/spool/mail 邮箱

/etc/group 存放组信息配置文件

组名密码占位符组标识GID用户

image.png

/home 家目录

/etc/shadow 存放用户密码的(第二列密码是经过加密处理的)

/etc/passwd 系统中的所有用户的信息

用户名密码占位符用户标识UID组标识GID描述用户的家目录登录shell

image.png

判断用户是否可以登录看登录shell

shell为/bin/bash、/bin/sh /、/usr/bin/bash以为看该用户可以登录到系统

shell为/sbin/nologin、/bin/nologin 都不能登录

2用户组

一个用户至少包含一个组

groupadd 组名 创建组

groups 组名 查看用户组

groupmod -n 新组名 旧组名 修改组名字

groupmod -g 新GID 组名 修改GID

gpasswd -a 用户 组名 添加用户到组

gpasswd -M 用户1用户2 组名 添加多用户到组

gpasswd -d 用户 组名 从组删除用户

groupdel 组名 删除组

用户提权

让普通用户具备管理员权限,执行管理员命令

  • 修改配置文件 /etc/sudoers

    visudo

    100行

  • 执行命令组管理

    系统中有一个组,自带的组,轮子组 wheel

    只要把普通用户加入到这个组,这个用户具备管理员权限

gpasswd -a 用户 wheel

userwd gpasswd -a 用户 wheel

useradd 在创建时候就指定附加组 -G useradd 用户 -G wheel

提权成功后执行命令时候子啊命令前面加sudo

8、linux系统管理权限

1基本权限UGO

UUser 用户 所有者

GGroup 组 所属组

OOther 其他人

-rw-r--r-- 1 root root 60 Mar 28 17.44 xingdian

xingdian文件对应的所有者root 1对应的所属组root2

基本权限针对文件:

r 读 4 读取文件的内容 cat vim/vi

w写 2 编辑该文件 vi vim写入文件

x 执行 1 执行该文件(脚本) bash sh ./ /

就算一个文件没有执行权限我们可以使用bash或者sh的命令执行文件但是如果一个文件没有执行权限不能用./或者执行文件

基本权限针对目录:

r :读目录的内容 ls

w创建和删除内容 touch mkdir rm

x切换目录 cd

关于删除目录下的内容,有没有权限删除,取决于目录的权限,跟目录里面我们要删除的文件或者目录没有关系

文件的默认权限是644

目录的默认权限是755

2权限的设置

修改基本权限chmod

数字方式chmod 564 xingdian //这个文件权限:所有者读和执行,所属组读和写,其他人读

字母方式: chmod u+x xingdian //增加给xingdian文件所有者增加x权限

chmod u=rwx passwd //赋值给passwd文件所有者赋值权限为rwx

扩展

chmod 777 /opt/dir -R

将/opt/dir目录下的所有内容设置权限为777包括dir1目录下的所有文件也包括了dir目录

chmod 644 /opt/dir/* -R

将/opt/dir/目录下所有内容设置权限为644包括dir1目录下的所有文件不包括dir目录

修改所有者所属组chown

chown user1000,group2000 xingdian

修改xingdian文件所有者为user1000,所属组为group2000

chown user1001 xingdian

修改xingdian文件的所有者为user1001

chown .group2001 xingdian

修改xingdian文件的所属组为group2001chgrp 该命令只能修改所属组)

chown user1000.group2000 /opt/dir -R

将/opt/dir目录下所有内容的所有者设置为user1000所属组为group2000包括dir1目录下的所有文件也包括了dir目录

chown user1001.group2001 opt/dir* -R

将/opt/dir目录下所有内容的所有者设置为user1001所属组为group2001包括dir1目录下的所有文件不包括了dir目录

3高级权限

1.suid权限给命令文件设置权限当给命令文件设置了suid权限后无论那个用户执行该命令都会变成这个命令文件所有者的用户去执行 符合 s 对象 u 文件

chmod u+s 命令文件

2.sgid权限组继承权限 对象 g 符号s 针对目录

目录的所属组假设是hr如果设定了sgid权限那么在该目录下创建的新文件都会继承目录的属组hr

chmod g+s 目录名

3.sticky权限防止别人误删除 符号 t 对象 o 针对目录

chmod o+t 目录名

4umask

umask 权限掩码 创建文件的时候文件默认权限跟umask有关联 默认情况下umask的值为022 所以创建的文件默认权限644目录默认权限755

修改umaskumask + 掩码 最大777 最小000

文件默认权限=0666-0022=0644

目录默认权限=0777-0022=0755

5文件属性隐藏权限

a能看 能追加 不能删除

i只能看其他啥也干不了

chattr + -

lsattr查看

9、进程管理

1静态ps

image.png

ps aux

第一列:进程的拥有者

第二列PID 进程ID 唯一标识一个进程

第三列cpu使用的百分比

第四列mem内存使用率

第七列:终端

第八列:进程的状态

Ss s进程的领导者父进程

S< <优先级较高的进程

SN N优先级较低的进程

R+ +表示是前台的进程组

Sl 以线程的方式运行

最后一列:进程的名字

ps aux --sort -%cpu | less 按照cpu使用率从大到小

ps aux --sort -%mem |less 按照mem使用率从大到小

ps aux --sort -%cpu | head -4 | grep -v USER > /tmp/1.txt 按照cpu使用率从大到小查看前四行去掉USER重定向到/tmp/1.txt上

grep -v 取反

pidof sshd 获取服务pid

lsof 服务的端口,服务运行,进程存在,服务不运行,进程不存在,进程一定在

lsof -i:80

w who 都可以看到谁正在远程链接我能够获取到对方ip地址、终端编号、对应的用户

w 还可以看服务器的运行时间、用户数量、平均负载

uptime 看cpu平均负载

2动态top

快捷键P将cpu使用率排序 M将%mem使用率排序 R排序反转

操作系统两种cpu状态 内核态 用户态

top分为上下两部分上面是机器整体负载情况下面是单个进程的负载情况

load average代表cpu每1分钟5分钟15分钟的平均负载

us 用户空间占用cpu的百分比

sy 内核空间占用cpu的百分比

ni 调整过优先级的进程占用cpu的百分比

id cpu空闲百分比

wa io等待占用cpu百分比

hi 硬中断占用cpu百分比

si 软中断占用cpu的百分比

free -m/h 看内存的使用率

total 总量 used使用量 free空闲量 buff/cache 缓存中的内存

3网络进程

netstat -auntpl

ss -auntpl

-a所有

-u查看upd进程

-ppid

-n显示数字

-l监听

-t查看tcp进程

ss -antpl # 显示所有的 TCP 连接和监听端口,以及与之相关联的进程信息 netstat -antpl # 显示所有的 TCP 连接和监听端口,以及与之相关联的进程信息 ss -tnupl # 显示所有的 UDP 连接和监听端口,以及与之相关联的进程信息

数据传输:

tcp传输控制协议

tcp状态

CLOSED(关闭状态)初始状态表示TCP连接未建立

LISTEN(监听状态)。服务器等待客户端连接的状态

SYN SENT(同步已发送状态)。客户端发送连接请求后等待服务器确认的状态。

SYN RECEIVED(同步已接收状态)。服务器接收到客户端连接请求并发送确认后的状态。

ESTABLISHED(已建立状态)。表示TCP连接已成功建立双方可以进行数据传输。

FIN WAIT 1(等待对方FIN报文状态)。表示TCP连接的一方发送了关闭连接请求。

FIN WAIT 2(等待对方关闭连接请求状态)。表示TCP连接的一方等待对方发送关闭连接请求。

TIME WAIT(等待状态)。表示TCP连接关闭后的等待状态用于确保数据的可靠传输。

CLOSE WAIT(等待关闭状态)。表示TCP连接的一方接收到了对方的FIN报文但尚未发送ACK。1

LAST ACK(最后确认状态)。表示TCP连接关闭前的最后确认状态等待对方的FIN报文。3

CLOSING(关闭状态)。表示TCP连接正在进行关闭过程

udp用户数据报协议

4进程管理

kill

kill -1 重新加载进程或重新加载配置文件

kill -9 给进程发送一个强行终止的信号

kill -15 正常杀死

kill -18 激活进程 //挂起在次激活时服务对应进程的PID会改变不能

kill -19 挂起进程

pkill

pkill -9 -t pts/2 //指定终端干掉

pkill -9 -u 用户 //干掉指定用户进程

10、文件描述符

1重定向

0 标准输入

1 标准正确输出

2 标准错误输出

$当前终端的PID echo$ 获取当前终端的PID

.> > 追加

.> 覆盖

1> 标准正确输出重定向覆盖

1>> 标准正确输出重定向

2> 标准错误输出重定向覆盖

2>> 标准错误输出重定向追加

& === 1+2 混合输出

cat >>/opt/xingdian.b <<eof

xingdian

diandian

hello

hi

eof

| 管道的作用 前一条命令执行后的结果交给后一条的执行

2sort

sort 排序 从小打到排序

-r 反转

-n 按照数值排序

-k 指定字段(按列分)

3uniq

uniq 去重复(只能对一个字段,必须要排序在去重复)

-c 统计

cat 1.txt | awk -F':' 'NR==10{print $5}' ##NR指定目标所在行

awk $NF 最后一列 $`(NF-1) 倒数第二列

-F 指定分隔符

grep -v 取反

access.log 日志文件 nginx访问日志

  1. 获取到所有的ip地址

    cat access.log | awk '{print $1}'

  2. 获取到所有ip的个数统计某一网站访问次数统计某一网站pv量

cat access.log | awk '(print $1)' | wc -l

  1. 获取所有的IP地址去重统计某个网站访问的人有那些

    cat access.log | awk '{print $1}' | sort -n | uniq

  2. 统计某一网站访问人数uv

cat access.log | awk '{print $1}' | sort -n | uniq | wc -l

  1. 每个ip地址的个数每次ip访问的次数

    cat access.log | awk '{print $1}' | sort -n | uniq

  2. 获取访问次数前三的人/ip地址

    cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -3

11、磁盘管理

机械硬盘HDD

固态硬盘SSD

分布式存储 HDFS CEPH

云存储

对象存储 minio OSS

1磁盘分区

lsblk 查看磁盘分区

MBR fdisk 命令最多分4个主分区

GPT gidsk 命令可以分128个主分区

磁盘大于2T不可以使用fdisk命令必须要用gdisk命令可以分128个主分区

fdisk

n添加分区

p主分区

e扩展分区

p查看分区

w保存退出

q退出不保存

gdisk

n添加分区1-128

p: 查看分区

d删除分区

w保存退出

q退出不保存

2格式化

文件系统

linux xfs ext4 ext3 nfs

windows NTFS FAT32

格式化:磁盘或者磁盘分区设定文件系统类型

磁盘有空间本身容量100G现在还显示10G但是无法存放数据ext家族文件系统inodes耗尽造成无法存储文件

mkfs.xfs -f 设备名称

mkfs.ext4 设备名称

mount 挂载

临时挂载:

mount 设备名称 挂载点(目录)

umount 设备名称 挂载点 (目录)

mount -o rw centos-7-x86 64-Minima1-2009.iso /opt/centos/ 把镜像挂载在opt/centos目录上 rw是读写权限

临时挂载重启失效

永久挂载:

vim /etc/fstab 添加相关参数实现永久挂载

第一列设备设备名称。设备uuid标识

第二列:挂载点(本质就是目录)

第三列文件系统类型xfs ext4 nfs

第四列: 属性 rw remount defaults

第五列+第六列: 0 0 不备份 不检查

/dev/sdc /opt/1 ext4 defaults 0 0

[root@fuxiaoshunc7 opt]# blkid /dev/sdb /dev/sdb: UUID="a78dc5f7-5092-4539-8d69-cdf5846de1ce" TYPE="xfs"

查找uuid

UUID="25d22b48-8e46-494b-a12c-ae80a4297808" /opt/1 xfs defaults 0 0

3物理卷 逻辑卷 卷组

物理卷

pvcreate /dev/磁盘名称(sdb) //创建物理卷

pvremove /dev/磁盘名称(sdb) //删除物理卷

pvs //查看物理卷

pvmove /dev/sdb /dev/sdd //数据迁移: sdb-->sdd

卷组

vgcreate 卷组名vg1/dev/磁盘名(sdb) //创建卷组

vgextend 卷组vg1 /dev/磁盘名(sdb) //将物理卷加入到卷组

vgremove 卷组名(vg1) //删除卷组

vgreduce 卷组名vg1 /dev/磁盘名(sdb) //将物理卷从卷组中移除

vgs //查看卷组

逻辑卷

lvcreate -L 磁盘容量大小(2G) -n 逻辑卷名(lv1) 卷组名(vg1) //创建逻辑卷

lvremove /dev/卷组名(vg1)/逻辑卷名(lv1) //删除逻辑卷

lvextend -L 磁盘容量(+5G) -n /dev/卷组名(vg1)/逻辑卷名(lv1) //逻辑卷扩容

lvreduce -L 20G /dev/centos/root //自定义逻辑卷的容量

lvs 查看逻辑卷

扩容/分区

  • pvcreate /dev/sdb //创建物理卷

  • vgextend centos /dev/sdb //将物理卷加入centos卷组

  • lvextend -L +5G /dev/centos/root //逻辑卷扩容5G

  • xfs_growfs 要扩容的lv的path(/dev/centos/root) //整合文件系统

    扩容完要整合文件系统

准备一个正在被使用LV并且文件系统ext4

   -  lvcreate -L 2G -n lv2 vg1
   -  mkfs.ext4 /dev/vg1/lv2
   -  mkdir /opt/lv2
   - vi /etc/fstab    /dev/vg1/lv2 /opt/lv2 ext4 defaults 0 0
   - mount -a   验证 df -Th
   - lvextend -L 5G /dev/vg1/lv2
   - 判断文件系统为ext4 所以使用
   - resize2fs /dev/vg1/lv2

逻辑卷格式化

先取消挂载

在删除逻辑卷

删除卷组

删除物理卷

格式化

4swap分区

swap分区大小设置规则

内存小于4G时推荐不少于2GB的swap空间

内存4GB~16GB推荐不少于4GB的swap空间

内存16GB~64GB推荐不少于8GB的swap空间

内存64GB~256GB推荐不少于16GB的swap空间

制作swap分区

先用fdisk做一个分区

格式化

mkswap /dev/sdb 格式化分区

swapon /dev/sdb 激活swap分区

swapoff /dev/sdb 关闭swap分区

swap分区 交换分区 防止内存溢出造成系统奔溃

内存 == 物理设备 === 内存条

swap == 交换分区 == 磁盘空间 充当 内存空间

物理内存8G

磁盘空间100G 分区 / 95G

/boot 1G

/swap 4G

5磁盘阵列

raid 0

raid 0分为2种分别为单盘0和全盘0

raid全盘0 最少需要2块盘 磁盘空间利用率为100% 没有冗余没有容错

raid0把连续的数据分散到多个磁盘上存取

raid单盘0 只需要一块磁盘 常用于新服务器安装操作系统

raid 1

raid 1 只能2块磁盘做。

镜像raid通过磁盘数据镜像实现数据冗余在成对的独立磁盘上产生互为备份的数据

优点:提供数据冗余,支持容错,读速度快

缺点:写速度慢,磁盘利用率不高 磁盘利用率50%

raid 5

raid5最少需要3块磁盘。它的校验数据分布在阵列中的所有磁盘上。

优点1.可以找回丢失的数据2.冗余磁盘当某一块磁盘坏掉后冗余磁盘会自动替换上去3.读写速度高4.磁盘利用率高

缺点1.磁盘越多安全性能越差

利用率 n-1/n

raid 6

raid6 两块存校验位。RAID6引入双重校验的概念

最少需要四块磁盘,它可以保护阵列中同时出现两个磁盘失效时,阵列仍能够继续工作,不会发生数据丢失。

优点1.容错:允许两块磁盘同时坏掉。读快。

缺点1.写入速度差

2.成本高

3 磁盘利用率 n-2/n

应用场景:对数据安全级别要求比较高的企业

raid1+raid5 全都是机械硬盘

raid1+raid5 机械盘+固态盘 混搭

raid1用机械装系统

raid5用固态存数据

raid1+ssd_raid5

raid 阵列选型: 根据服务特点和数据相关做有冗余的阵列数据要求极高的就做最高的安全性raid。

根据业务特点数据重要程度去选择冗余度高和低的raid阵列

6文件链接

软连接

ln -s 源文件(/roo/zhangsan) 目的地(/opt)

普通文件和目录都支持软连接

软连接源文件跟链接文件inode号不同

软连接源文件删除后,链接文件不可用

软连接可以跨分区

硬链接

ln 源文件 目的地

文件可以创建硬链接,目录不可以

硬链接inode不变

硬链接源文件删除后,链接文件可以使用

硬链接不可以跨分区

12、文件查找

(1)find

语法格式:

find 位置/路径 条件 值 动作

条件:

正则: .* 任意多个字符 [0-9] [0-9z-a] [A-Z] [0-9A-Z] []

-name //文件名字

-type //文件类型 普通文件 f 其他和文件类型一样

-size //文件大小 +5M 大于5M 5M 在5M范围内

-user //查找所有者

-group //查找属组

-perm //权限 指定 644 755

-mtime //修改时间

atime //访问时间 ctime 改变时间 mtime 修改时间

多个条件:

-a and // 条件都要满足

-o or //条件满足其中一个

动作: 默认-print 显示详情信息 -ls

-delete 删除

-exec

*find /opt -name "3" -exec mv {} /mnt ;

-exec ; 格式

{} 承接查到的内容

-ok

find /opt/ -name "*3" -exec mv {} /mnt ;

mv 文件操作命令

{}承接查到的内容

-ok ; 格式

|xargs

find /opt/ -name "*2" |xargs -i mv {} /mnt

(2)压缩 解压

windows .rar .zip

linux.zip .tar.gz .tar.bz2 .tar.xz

tar包

之所以会得到不同格式的压缩包,因为调用的压缩方式不同

.tar.gz gzip z

.tar.bz2 bzip2 j

.tar.xz xz j

打包压缩tar cf 路径/压缩包的名字 压缩的文件

解压缩tar xf 压缩包名字

指定位置解压: -C

tar tf 不解压直接查看内容

tar -r 命令会在tar文件的末尾添加新的文件或者目录而不会修改已有的文件

查看/etc目录下所有以.conf结尾的文件并进行压缩压缩到/opt目录下命名为conf.tar.gz

find /etc -name "*.conf" |xargs -i tar rf /opt/conf-1.tar.gz{}

zip包

解压缩unzip 压缩包名字

指定位置解压: unzip -d /opt/ nextcloud-22.0.0.zip

gunzip 解压.gz结尾的包 如果没有gunzip,使用yum -y install gzip

13、软件包管理

二进制包 .rpm结尾 有依赖关系 网站 https://rpmfind.net(注意版本) 软件官网mysql

rpm -qa | grep 服务名 找安装包

rpm -ql 服务名 启动服务

源码包 .tar.gz tar.xz

ntfs-3g-2011.4.12-5.e15.x86 64.rpm

软件名字 版本号 发行版本 平台架构 后缀

etc/yum.repos.d

Centos-Base.repo 基础仓库文件 BASE仓库

扩展仓库文件 EPEL仓库

仓库文件里提供的是包下载地址(国外)

初始化的操作更换yum仓库或者更换yum源

自带删除 rm -rf /etc/yum.repos.d/*

阿里 腾讯 华为 网易 基础源

阿里巴巴开源镜像站-OPSX镜像站-阿里云开发者社区 (aliyun.com)

在系统中有一些软件BASE和EPEL仓库中没有来自于软件官网

BASE和EPEL中mariadb没有mysql

数据库 mysql

mysql 仓库文件所对应的安装包安装该包就能得到mysql的放库文件

yum -y install https://dev.mysql.com/get/mysq180-community-release-el7-11.noarch.rpm

web服务器 nginx

vi /etc/yum.repos.d/nginx.repo

[nginx-stable]

name=nginx stable repo baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true

[nginx-mainline] name=nginx mainline repo baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/ gpgcheck=1 enabled=0 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true

1yum

yum 软件包管理的命令

install [yum -y install sl]

remove [yum -y remove sl]

reinstall [yum -y reinstal sl]

yum provides 包名 查找包名

yum info 服务名 查找包的详细信息

yum -y update 服务名 更新服务

yum list 列出所有包

yum repolist 列出所有的仓库(可用仓库)

组包

grouplist

groupinstall

清空yum缓存在重新加载yum缓存[加快软件的安装速度]

yum clean all

yum makecache //生成缓存 或者 yum makecache fast 快速生成缓存

yum list -h | grep show

yum list --showduplicates docker-ce服务名全称 列出你可以安装的版本都有哪些

yum -y install docker-ce-3:20.10.12-3.el7 指定版本安装

详情:
     是一个在 Linux 系统中使用 yum 包管理器的命令。这个命令用于列出所有可用的软件包,并显示重复的软件包。

     这个命令的输出会包含很多行,每一行代表一个软件包。如果有多个版本的同一软件包可用,它们都会被列出来。
 
     这个命令的使用场景可能是在你需要查看所有可用的软件包版本,或者你需要知道你的系统上安装了哪些重复的软件包版本。

yum仓库

[base]

name=CentOS-$releasever - Base - mirrors.aliyun.com //指定仓库的名字

baseurl=http://mirrors.aliyun.com/centos/ //仓库地址

enabled=1 // 1开启 0关闭 仓库是否启用

gpgcheck=1 // 是否校验 1开启 0关闭

gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7 //

2rpm

rpm -ivh 软件包 // s1-5.02-1.e17.x86 64.rpm

卸载 rpm -e s1-5.02-1.e17.x86 64.rpm

查询 rpm -qa 获取已经安装的所有包

3源码包

源码编译安装nginx

 源码编译安装nginx https://nginx.org/ nginx的官网

1.获取nginx的源码包

wget https://nginx.org/download/nginx-1.24.0.tar.gz

tar xf nginx-1.24.0.tar.gz

2.编译安装准备所需要的环境

yum -y install apr apr-util ncurses ncurses-devel openssl-devel bison gcc gcc-c++ make

3.配置

./configure  --prefix=指定位置(/opt/nginx

4.编译

make

5.安装

make install

获取项目源码包wget http://10.9.12.206:30120/directlink/1/safeware/love.zip 安装解压工具yum -y install unzip 解压源码包unzip love.zip 拷贝源码到网站发布目录下cp -r love/* /opt/nginx/html/

启动nginx : /opt/nginx/sbin/nginx 执行的是安装目录下的sbin目录下nginx的文件 关闭nginx killall -9 nginx

访问之前关闭防火墙和selinux systemctl stop firewalld systemctl disable firewalld setenforce 0 vim /etc/sysconfig/selinux.conf SELINUX=disabled

14、网络协议

(1)OSI、tcp/ip参考模型

早期的网络设备:中继器、多协议网关(路由器前身)

ISO 国际标准化组织 OSI开放式系统互联一套标准TCP/IP传控制协议/网际协议

网络的设计:带宽高、安全性强、可用性强、时效性、完整性、准确性

OSI七层模型

物理层: 约定接口类型、传输速度 数据---比特流0.1)发送出去

传输媒介: 双绞线网线rj45

数据链路层: MAC物理地址烧写在网卡设备上 唯一性 唯一标识一台设备

网路层:路由和选路

IP地址

传输层:约定数据采用何种方式

TCP传输控制协议

UDP用户数据报协议

会话层:建立删除维护会话

表示层:数据的格式,数据加密解密等

应用层:针对于应用约定的标准

HTTP 超文本传输协议 Telnet远程协议 QICQqq协议

HTTPS 安全超文本传输协议 STMP\POS3

(2)tcp/IPv4协议 4层/5层

tcp/ipv4 4层模型

应用层(应用层+表示层+会话层)

传输层

网络层

网络接口层 (物理层+数据链路层)

tcp/ipv4 5层模型

应用层(应用层+表示层+会话层)

传输层

网络层

数据链路层

物理层

数据封装和解封装的过程

封装:发送数据的过程

解封装:接受数据的过程

数据封装将上层数据添加各层协议,首部形成数据包

数据解封装根据协议首部信息,逐层剥离各层协议首部,并提取出应用层数据.

image-20240415112108523

wireshark 抓包工具

网关地址:只选择两个地址作为网关地址:.1 .254

vmware nat模式的虚拟机 .2

(3)tcp和udp

tcp传输控制协议 面向连接协议 传输可靠 重传机制

1.建立链接 TCP链接

TCP报文中的指针如果TCP报文被标注为ACK该TCP的报文就是确认消息的报文

SYN同步消息 建立连接时发送SYN

ACK确认消息

tcp三次握手

第一次握手建立连接时客户端发送syn包到服务器并进入syn_sent状态等待服务器确认

第二次握手服务器收到SYN包必须确认客户的SYN同时也发送一个syn+ack包此时服务器进入syn_rcvd状态

第三次握手客户端收到服务器的SYN+ACK 包向服务器发送确认包ACKack=k+1此包发送完毕客户端和服务器进入established状态完成三次握手客户端与服务器开始传送数据

2.断开链接 TCP链接

客户端向服务器发送断开连接的请求

服务器收到后回复ACK

服务器向客户端发送的断开连接的请求

客户端收到后回复ack

udp用户数据报协议 非面向连接的协议 传输不可靠

udp传输速度更快

(4)wmare 网络模式

仅主机(不用)

桥接:桥接模式创建出来的虚拟机跟宿主机属于同一个网络,虚拟机相当以局域网中独立的设备

NATNAT模式创建出来的虚拟机有自己独立的网络能跟宿主机互相通信但是不能访问其他主机中NAT模式的虚拟机

如果虚拟机没有网络,排查思路

1.网卡 VMNET1 VMNET8

2.此电脑-管理-服务-vmware相关服务器是否处于运行状态

路由

1.直连路由

2.静态路由

3.动态路由

开启linux的路由转发功能

vim /etc/sysctl.conf

net.ipv4.ip_forward = 1

sysctl -p 生效

yum -y install net-tools 安装route

image.png黄色标识:内网网关

arp 192.168.0.1 //看内网网关的mac地址

arp协议将ip地址解析成mac地址

(5)ip地址

IP地址

两部分: 网络部分(网络位) 主机部分(主机位)

10.9.25.42 4部分数字 点隔开 8位二进制数 0 1

1000001010

128 64 32 16 8 4 2 1

配置网络

临时

ip a a dev 网卡名称 IP地址/子网掩码

ip address add

ip a d dev 网络名称 IP地址/子网掩码

ip address delete

ifconfig 网卡名称:序号 IP地址/子网掩码

ipconfig 网卡名称 IP地址/子网掩码 [修改原有地址]

永久

网卡配置文件重要使用配置文件etc/sysconfig/network-scripts/ifcfg-

静态ip地址-转换成动态- dhcp

BOOTPROTO="dhcp" TYPE="Ethernet" NAME="ens33" DEVICE="ens33" ONBOOT="yes"

systemctl restart network

动态ip转换成静态ip

BOOTPROTO="none" TYPE="Ethernet" NAME="ens33" DEVICE="ens33" ONBOOT="yes" IPADDR=X.X.X.X NETMASK=255.255.255.0 GATEWAY=x.x.x.2 DNS=x.x.x.2

systemctl restart network 重启网卡(网络服务)

192.168.72.x/24 网关地址和dns地址都是192.168.72.2 (虚拟机) 10.9.27.x/24 网关地址和dns都是 10.9.27.1 (企业)

(6)bond0动态链路聚合

1.添加网卡设备 1台服务器3网卡

2.cp /etc/sysconfig/network-scripts/ifcfg-ens33 /etc/sysconfig/network-scripts/ifcfg-ens33.bak

cp /etc/sysconfig/network-scripts/ifcfg-ens33 /etc/sysconfig/network-scripts/ifcfg-ens36.bak

cp /etc/sysconfig/network-scripts/ifcfg-ens33 /etc/sysconfig/network-scripts/ifcfg-ens37.bak

3.网卡模板(所有网卡文件都要修改) [root@xingdian network-scripts]# vim ifcfg-ens33 BOOTPROTO=none DEVICE=ens33 #网卡名称注意别填错 ONBOOT=yes USERCTL=no #普通用户是否可控制此设备 MASTER=bond0 # 绑定聚合文件ifcfg-bond0 SLAVE=yes

4.聚合模版文件 [root@xingdian network-scripts]# vi /etc/sysconfig/network-scripts/ifcfg-bond0 DEVICE=bond0 ONBOOT=yes USERCTL=no BONDING_OPTS="mode=1 miimon=100 fail_over_mac=1" BOOTPROTO=none IPADDR=10.0.0.128 NETMASK=255.255.255.0 GATEWAY=10.0.0.2 ZONE=public DNS1=114.114.114.114

系统每100ms 监测一次链路连接状态 默认fail_over_mac=0当发生错误时只改slave的mac不改bondfail_over_mac=1时只改bond不改slave

5.重启网络服务 [root@xingdian network-scripts]# systemctl restart network

6.查看绑定结果 [root@xingdian network-scripts]# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1 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: ens33: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master bond0 state UP qlen 1000 link/ether 00:0c:29:a6:32:2d brd ff:ff:ff:ff:ff:ff 3: ens36: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master bond0 state UP qlen 1000 link/ether 00:0c:29:a6:32:2d brd ff:ff:ff:ff:ff:ff 4: ens37: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master bond0 state UP qlen 1000 link/ether 00:0c:29:a6:32:2d brd ff:ff:ff:ff:ff:ff 5: bond0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000 link/ether 00:0c:29:a6:32:2d brd ff:ff:ff:ff:ff:ff inet 10.0.0.128/24 brd 10.0.0.255 scope global bond0 valid_lft forever preferred_lft forever inet6 fe80::20c:29ff:fea6:322d/64 scope link tentative dadfailed valid_lft forever preferred_lft forever

7.查看bond信息 [root@xingdian network-scripts]# cat /proc/net/bonding/bond0

注意: 如果没有加载模块,需要加载模块 [root@xingdian ~]# lsmod |grep bonding [root@xingdian ~]# modprobe bonding [root@xingdian ~]# lsmod |grep bonding bonding 152656 0

Mode 0 (balance-rr) 轮转Round-robin策略从头到尾顺序的在每一个slave接口上面发送数据包 Mode 1 (active-backup) 备份主备策略只有一个slave被激活仅当活动的slave接口失败时才会激活其他slave

ifdown ens33 down掉bond0绑定的网卡 自动切换到另外一个网卡
开启新的服务器进行访问测试切换后依然可以访问那说bond成功了

ifup 激活

15、服务管理

(1)服务管理

故障排查思路:

如果给httpd服务增加功能修改配置文件。写错了参数

启动httpd systemctl restart httpd 报错 没有启动成功

systemctl status httpd -l 获取报错原因

(2)时间服务

时间服务器NTP

timedatectl set-timezone Asia/Shanghai 设置时区为上海

ntpdate ntp.aliyun.com 同步时间阿里云

一 、环境准备:

1.修改主机名

hostnamectl set-hostname ntp-server

关闭防火墙和selinux

systemctl stop firewalld

systemctl disable firewalld

setenforce 0

二、配置时间服务器

# rpm -qa | grep ntp

ntp-4.2.4p8-3.el6.x86_64

yum -y install ntp

NTP Server配置示例

# vim /etc/ntp.conf //配置文件全部删掉,只要下面三行

restrict default nomodify //不允许客户端登录,也不允许客户端修改

server 127.127.1.0 //使用本地的bios时间自己跟自己同步

fudge 127.127.1.0 stratum 10 //定义级别范围0-16越小越精准

# systemctl restart ntpd

# systemctl enable ntpd

三、配置NTP客户端

yum -y install ntpdate

# ntpdate -b 172.16.110.1 //手动时间同步 -b加速初始化同步

(3)日志管理

日志服务rsyslog

/var/log//默认是系统用来存放日志的目录,默认情况下服务。系统的日志文件都在该目录下

/etc/rsyslog.conf//日志服务配置文件

/etc/rsyslog.d //日志服务的子配置文件

messages //系统主日志文件

secure //认证、安全

cron//计划任务的日志

yum.log记录yum相关日志安装+卸载)

grep Accepted /var/log/secure 过滤登录成功 grep Failed /var/log/secure 过滤登录失败

日志级别 级别越低,信息越多

debug最低的一般不用

info安装信息警告信息错误信息

notice相当与提示

warn/warning警告错误

error/err错误严重错误

alert告警表示已经出现问题

emerg恐慌级别

扫描端口

yum -y install nmap 端口扫描 查看服务器开放的端口

nmap -O 192.168.21.163 #探测目标主机操作系统类型 nmap -A 192.168.21.163 #探测目标主机操作系统类型

(4)日志轮转

对象:日志文件

为什么:防止日志文件过大

避免无法打开过慢 避免浪费磁盘资源

定期清理 旧的日志数据/文件

这么做日志切割? 利用规则切割 日志切割

logrotate 依据 规则文件

/etc/logrotate.conf 规则配置文件 (决定每个日志文件如何轮转)

子配置目录 /etc/logrotate.d/ ##存放特定应用或服务的单独配置日志文件

/var/log/wtmp{

yearly //达到一年就轮转一次,两者满足一个就轮转

weekly //轮转的周期,一周轮转

monthly //一月轮转一次

daily //一天轮转一次

create //轮转后创建新文件

dateext //使用日期作为后缀

minsize 1M //最小达到1M才轮转即到了规定的时间未达到大小不会轮转

maxsize 30k //达到30k就轮转

create 0664 root utmp //轮转后创建新文件,并设置权限属主和属组

rotate 1 //保留一份

missingok //丢失不提示

notifempty //空文件不轮转

}

logrotate.conf -f /etc/logrotate.d/qfssh.log 强行轮转一次

(5)计划任务

计划任务

at一次性计划任务

一次性计划任务:

安装对应的软件yum -y install at

启动 systemctl restart atd

两部分

时间:只能指定某一个时间点

任务/命令/动作

案例:

在1422分执行创建文件的命令

at 1422 //时间

.>touch /opt/xingdian //任务、命令

.>ctrl +d 结束计划任务创建

100 5/1/2024 小时:分钟 月:日:年

at -l 查看计划任务 at -d 任务序号

crontab循环性计划任务 crontab执行时间计算 (https://tool.lu/crontab/)

服务crond systemctl status crond 默认开机自启

分类:

系统级计划任务

用户级计划任务(超级管理员 普通用户)

创建 */1 * * * * //每一分钟 crontab -e

查看 //查看计划任务crontab -l

删除 //删除计划任务crontab -r

// 指定用户删除crontab -r -u xingdian

/var/spool/cron 里面存放了循环计划任务的文件 以用户命名

16、ftp服务

服务端:

1.yum -y install vsftpd

2.systemctl restart vsftpd systemctl enable vsftpd

3.浏览器或者文件资源管理器访问测试

客户端:

1.yum -y install lftp

lftp 192.168.12.122

/etc/vsftpd/vsftpd.conf //vsftpd配置文件

/var/ftp/ //对外共享目录,要共享的文件放到该目录下

/var/log/xferlog 用户的上传和下载都会被该文件记录 vsftpd日志文件

mirror 下载目录 get 下载文件

(1)开启匿名用户上传模式

1.有一个目录,在对外的共享目录下,而且该目录必须还得创建文件/目录权限(默认的对外共享目录)

mkdir /va/ftp/date

chmod 777 /var/ftp/date

2.修改文件实现上传功能

anon_upload_enable=YES # 是否允许匿名用户上传文件 anon_mkdir_write_enable=YES # 是否允许匿名用户允许创建目录

3.验证上传功能

lftp 10.9.12.122

put +文件名(绝对路径)上传的文件本地有

mirror -R 目录名(绝对路径) 上传的目录本地有

注意: 1.对外共享目录自身不能使用777权限否则会报错 2.上传文件前先要进入对应的目录下,否则无法上传 3.所有服务器都要关闭防火墙和SELinux

(2)自定义匿名用户共享目录

1.创建对外共享目录

mkdir /opt/gongxian

2.ftp指定该目录(修改配置文件)

anon_root=/opt/gongxiang //在某尾添加一行

3.重启服务

systemctl restart vsftpd

4验证

lftp

3.因需要使用/opt/nfs-share目录最为FTP对外共享目录该目录下有一子目录为data,实现匿名用户在该目录下可以上传下载文件

(3)启用FTP用户登录

  1. useradd zhangsan

    passwd 123

  2. 修改配置文件开启普通用户登录的功能

local_enable=YES

3.验证 lftp 10.9.12.122 -u zhangsan

普通用户登录FTPftp的服务器端来说对外共享的目录默认是普通用户的家目录

(4)所有的普通用户使用同一个对外共享目录

1.创建共享目录 mkdir /opt/qf2402

2修改配置文件指定共享目录 local_root=/opt/qf2402

3重启服务

4验证(在共享目录下创建一个文件,方便验证)

[root@ftp-client ]# lftp 10.9.12.122 -u xingdian Password: lftp xingdian@10.9.12.122:> ls
-rw-r--r-- 1 0 0 0 Apr 19 06:35 qf2402.txt lftp xingdian@10.9.12.122:~> exit [root@ftp-client ~]# lftp 10.9.12.122 -u cloud Password: lftp cloud@10.9.12.122:~> ls
-rw-r--r-- 1 0 0 0 Apr 19 06:35 qf2402.txt lftp cloud@10.9.12.122:~>

(5)普通用户上传文件

1.在对外共享目录下创建一个目录,并设置 777权限

mdir /opt/qf2402/qf

chmod 777 /opt/qf2402/qf

2.修改配置文件,开启上传功能

anon_upload_enable=YES anon_mkdir_write_enable=YES

3.重启服务

4.客户端就可以使用普通用户上传文件

(6)黑白名单

ftpusers user_list

userlist_deny=YES 用户不在 user_list 文件中 该用户可以访问FTP

userlist_deny=YES 用户在 user_list 文件中 该用户不可以访问FTP

userlist_deny=NO 用户在 user_list 文件中 该用户可以访问FTP

userlist_deny=NO 用户不在 user_list 文件中 该用户不可以访问FTP

userlist_deny=NO 用户在 user_list 文件中 例如root用户但是仍然不可以访问FTP root用户还在ftpusers中

(7) ftp+自制yum源

1.在FTP-Server安装FTP服务

安装并运行(开机自启--不强制)

2.采用匿名用户访问,对外共享目录/var/ftp 自定义的对外共享目录 在共享目录下创建一个目录用来存放RPM包

目录创建:略
准备包:略  [包从镜像获取]
拷贝包:略  拷贝到对外共享目录下自己创建的目录

3.将该目录变成软件包目录

createrepo命令将存放rpm的包变成软件包目录

4.客户端调用 ftp://10.9.12.122 yum调用

/etc/yum.repos.d/centos.repo

[xingdiancloud] name=xingdiancloud package baseurl=ftp://10.9.12.122/centos7 enabled=1

17、NFS服务

NAS 网络附加存储 NFS

NFS 属于NAS存储的软件又是一个网络文件系统 linux和linux之间共享

NFS 对外共享的是文件系统 客户端需要 挂载才能使用

Samba SMB协议 C/S架构/模型 资源共享和打印机服务 Linux和Linux Linux和Windows

2台服务器

一台NFS-server

二台 NFS-client

服务器配置:

1.安装

yum -y install nfs-utils

2.启动并开机启动

systemctl restart nfs

systemctl enable nfs

3.创建对外共享目录

mkdir /opt/share-1

4.配置对外共享 /etc/exports

只读

共享源 共享给谁 共享属性 /etc/exports

/opt/share-1 *(ro,sync,no_root_squash)

        [root@nfs-server ~]# exportfs -rv
		exporting *:/opt/share-1
		[root@nfs-server ~]# systemctl restart nfs

共享给谁

        /opt/share-2 10.9.12.0/24(ro,sync,no_root_squash)  共享给一个网段

		/opt/share-2 10.9.0.0/24(ro,sync,no_root_squash)   共享给某一个人

		/opt/share-1 *(ro,sync,no_root_squash)  共享给所有人

读写

/opt/share-4 *(rw,sync,no_root_squash)

客户端配置

1.保证系统支持网络文件系统NFS

yum -y install nfs-utils

2.使用NFS-server端对外共享的资源挂载挂载点

mkdir /opt/nfs-1

临时挂载

mount

永久挂载

/etc/fstab

10.9.12.122:/opt/share-1 /opt/nfs-1 nfs defaults 0 0

mount -a

验证:服务端创建文件,客户端验证是否同步 属性(只读 读写)

18、web服务

集群架构

web服务器nginx apache H5

中间层服务器提供JAVA PHP Python 运行环境

数据库服务器mysql 存储项目数据

web服务器 接受来自用户的请求,根据用户的请求做出响应

客户端 服务器 http超文本传输协议 https加密的超文本传输协议 密文

https SSl协议 证书 对服务器身份验证 客户端和服务器中间数据加密传输

URI统一资源标识符

URL统一定位符号 定位到文件地址

URI包含URL

H5 前端开发语言 项目 运行环境 apache nginx web服务器软件

JAVA 后端开发语言 项目 运行环境 web中间件

打包构建:两种情况

LNMP架构针对于java开发的项目

war包 shopping.war tomcat 软件运行 web中间件

war包架构LAMJT linux+apache/nginx+mariadb/mysql+jdk+tomcat

jar包 shopping.jar jdk java环境

jar包架构LAMJ linux+apache/nignx+mariadb/mysql+jdk

php php

python wsgi和uwsgi

中间件web中间件 java中间件 python中间件 php 中间件

消息队列中间件 RabbitMQ

(1)http服务

1.部署

yum -y install httpd

2.使用

systemctl restart httpd

systemctl enable httpd

3.目录和文件

/var/www/html apache自带默认网站发布目录 项目源码 自定义网站发布目录

	/etc/httpd/conf/httpd.conf  apache主配置文件

	/etc/httpd/conf.d/      apache子配置文件目录

	/var/log/httpd/			apache日志

	/var/log/httpd/access_log 	访问日志   /etc/httpd/logs/

	/var/log/httpd/error_log	错误日志


	存放在网站发布目录下,index.html    默认主页


	默认端口号 80

4.如何apache是否已经安装

rpm -qa | grep httpd

5.如何apache是否出运行状态

       systemctl status httpd

	ps aux | grep httpd 存在进程说明处于运行状态

	lsof -i:80 判断80端口是否存在

6.apache是web服务器软件所有的前端源码都可以在apache上运行

7.网站服务器 对外共享文件资源

mkdir /var/www/html/download

	 touch /var/www/html/download/file{1..10}

8.命令测试服务器是否正常运行

    curl  IP地址/域名

	elinks  IP地址/域名  文本的形式


	127.0.0.1  域名 localhost

9.apache主配置文件

		Listen 80 监听端口

		ServerRoot  /etc/httpd/

		DocumentRoot "/var/www/html"  网站发布目录

		<Directory / >  设置目录的属性 Require all denied 拒绝 </Directort> 

		Require all granted 允许

		ErrorLog "/etc/httpd/logs/error_log" 指定错误日志

		<IfModule log_config_module> 定义日志格式  </IfModule>

		CustomLog "logs/access_log" combined  定义访问日志  存放位置及文件名 格式的名字

		IncludeOptional conf.d/*.conf  加载子配置文件

实验

apache虚拟主机

	可以实现在一台服务器部署多个项目

基于端口
基于域名
基于IP地址

	三种方式使用那种都可以,但是选择其中一种后,剩余的保持一直

1.将项目上传到服务器

2.配置虚拟主机 [root@VM-0-5-centos conf.d]# cat a.conf b.conf c.conf

image-20240423145430788

<VirtualHost *:81>

    ServerName localhost
    DocumentRoot /web-1
     </VirtualHost>
<Directory /web-1>

    AllowOverride all
    Require all granted
     </Directory>

<VirtualHost *:82>

    ServerName localhost
    DocumentRoot /web-2
    </VirtualHost>
    <Directory /web-2>

    AllowOverride all
    Require all granted
    </Directory>

<VirtualHost *:83>

    ServerName localhost
    DocumentRoot /web-3
     </VirtualHost>
    <Directory /web-3>

      AllowOverride all
    Require all granted
    </Directory>

3.创建项目对应的网站发布目录 [root@VM-0-5-centos conf.d]# mkdir /web-1 [root@VM-0-5-centos conf.d]# mkdir /web-2 [root@VM-0-5-centos conf.d]# mkdir /web-3

4.将源码解压,拷贝到对应的网站发布目录下

6.添加对应端口的监听

81 82 82

Listen 81
Listen 82
Listen 83

5.重启服务

6.访问

IP+端口

(2)http日志

apache日志

定义日志格式

https://httpd.apache.org/docs/2.4/mod/mod_log_config.html

LogFormat 定义日志格式

指定配置日志

日志内容

给你一个日志文件利用awk sort uniq grep head cat wc 等命令进行分析 apache/nginx的访问日志文件

1.统计该网站有多少次访问记录

cat access.log | wc -l

2.统计一个每个IP访问了多少次

cat access.log | awk '{print $1}'| sort | uniq -c | sort -rn

3.统计每个请求方式的数量 GET有多少次 POST有多少次

cat access.log | awk -F '"' '{print $2}' | awk '{print $1}' | sort | uniq -c

cat access.log | awk -F'"' '{print $2}' | grep POST | wc -l cat access.log | awk -F'"' '{print $2}' | grep GET | wc -l

4.统计每一请求地址的访问次数 [root@proxy nginx]# cat access.log |awk -F'"' '{print $2}' |awk '{print $2}' |sort |uniq -c [root@proxy nginx]# cat access.log |awk -F'"' '{print $2}' |awk '{print $2}' |sort |uniq -c |sort -rn -k 1 | head

5.统计每个状态码的数量 200有多少个 404有多少个

cat access.log | awk -F '"' '{print $3}' | awk '{print $1}' | sort | uniq -c

cat access.log | awk -F'"' '{print $3}' | awk '{print $1}' | grep 200

cat access.log | awk -F'"' '{print $3}' | awk '{print $1}' | grep 404

(3)LAMP架构

LAMP架构 ==linux+apache+mysql/mariadb+php

L:linux

A:apache

M:mysql maridb

P:php

1博客 wordpress 项目 免费获取项目的源码 php语言开发

1.安装LAMP架构

[root@wordpress ~]# yum -y install httpd mariadb mariadb-server php php-fpm php-mysql php-gd gd

2.启动LAMP架构

systemctl start httpd mariadb php-fpm
systemctl enable httpd mariadb php-fpm (可选)

3.对服务进行配置apache、mariadb、php均采用默认的配置

apache不做修改 网站发布目录采用默认/var/www/html  端口默认80

mariadb用默认的但是需要准备一些东西  【库】  默认管理员用户(root)没有密码,为了安全设定一个密码

设定密码:[root@wordpress ~]# mysqladmin  -u root password '123'
进入数据库:[root@wordpress ~]# mysql -u root -p123
创建库MariaDB [(none)]> create database wordpress;

php不做修改 采用默认配置

4.上传项目源码,并将该源码放到网站发布目录下

[root@wordpress ~]# wget http://10.9.12.206:30120/directlink/1/safeware/wordpress-4.9.1-zh_CN.tar.gz
[root@wordpress ~]# cp -r wordpress/* /var/www/html/

5.设置源码权限

[root@wordpress ~]# chmod  777 /var/www/html/* -R

6.访问测试

LNMP架构

扩展针对java开发的项目

war包   L A/N M J T  linux+apache/nginx+mariadb/mysql+jdk+tomcat
jar包   L A/N M J    linux+apache/nginx+mariadb/mysql+jdk

(4)DNS

以下是 DNS 请求的全过程,包括根域名服务器的参与:

  1. 输入网址

    用户在浏览器中输入网址例如www.example.com并按下回车。

  2. 本地 DNS 缓存查询

    计算机首先检查本地 DNS 缓存,看看是否已经保存了该域名对应的 IP 地址。

  3. 向本地 DNS 服务器发起请求

    如果本地 DNS 缓存中没有找到对应的 IP 地址,计算机会向本地 DNS 服务器发起请求。

  4. 递归查询开始

    本地 DNS 服务器开始递归查询过程,向根域名服务器发起查询请求。

  5. 向根域名服务器查询

    根域名服务器知道整个互联网的域名分布情况,但它不知道具体域名对应的 IP 地址。根域名服务器会将查询转发给顶级域名服务器。

  6. 向顶级域名服务器查询

    顶级域名服务器知道每个顶级域名(如.com、.net、.org等的权威 DNS 服务器地址。本地 DNS 服务器向顶级域名服务器查询该域名的权威 DNS 服务器的 IP 地址。

  7. 向权威 DNS 服务器查询

    顶级域名服务器返回权威 DNS 服务器的 IP 地址后,本地 DNS 服务器向权威 DNS 服务器发起查询请求,请求该域名对应的 IP 地址。

  8. 返回 IP 地址

    权威 DNS 服务器查询到该域名对应的 IP 地址后,将其返回给本地 DNS 服务器。

  9. 返回给客户端

    本地 DNS 服务器收到 IP 地址后,将其缓存,并将其返回给客户端(例如您的计算机)。客户端收到 IP 地址后,就可以使用它来建立与目标网站的连接,开始浏览网页或进行其他网络活动。

(5)密钥远程管理服务

ssh服务

/etc/ssh/sshd_config 服务端配置文件

/etc/ssh/ssh_config 客户端配置文件

/root/.ssh/ 密钥存放位置

ssh 远程登录命令

ssh 192.168.17.168

ssh-keygen 生成密钥

密钥: id_rsa私钥 id_rsa.pub公钥 authorized_keys (存放对方的公钥)

scp

scp id_rsa 192.168.17.132:/root 拷贝私钥到B机器

实验:免密登录

1.生成密钥 ssh-keygen

2.你要去免密谁,给你发送你的密钥(公钥)

  1. ssh-copy-id 10.9.12.121

    4.ssh 10.9.12.121

实验:虚拟机使用密钥连接(远程工具)

1.生成密钥

2.将公钥写入到authorized_keys的文件中.ssh

cat id_rsa.pub >> authorized_keys

3客户端使用私钥登录获取到对应的私钥

指定私钥的方式连接服务

scp 远程拷贝 A B

1.把文件拷贝给别人

	scp -r  源文件    谁IP:路径   拷贝到对方的那个目录下

2.从别人哪里获取文件

	scp -r 对方IP:文件路径   放那个目录下

注意: 1.远程拷贝目录的时候,加-r参数 2.如果服务器之间做了免密,远程拷贝也是免密的

二.数据库mysql

1.数据库分类

关系型数据库sqlmysql Oracle sql-Server Mariadb

非关系数据库(NoSql)Redis MongoDB

(1)数据库访问技术

项目后端 如何 访问数据库

java

JDBC

实战项目后端源码中添加数据库的相关信息数据库ip地址 数据库端口 数据库用户名 数据库密码 数据库名

php

ODBC

实在项目后端源码中添加数据库的相关信息: 数据库IP地址 数据库端口 数据库用户名 数据库密码 数据库库名

python

settings.py

实在项目后端源码中添加数据库的相关信息: 数据库IP地址 数据库端口 数据库用户名 数据库密码 数据库库名

产品上线 产品发布 app 网站

需要提供数据库集群环境;[数据库IP地址 数据库端口 数据库用户名 数据库密码 数据库库名] ---> 后端 写入到自己的项目源码中 --> 构建 -->运维工程师 --> 产品上线

(2)yum安装数据库

Mysql版本

最新版本8

旧版本/前一个版本5.7

安装: 在BASE和EPEL仓库中没有Mysql的RPM包但是有Mariadb的RPM包

1.准备Mysql的yum仓库

[root@mysql-rpm ~]# yum -y install https://dev.mysql.com/get/mysql80-community-release-el7-11.noarch.rpm

2.修改安装版本,启用5.7版本

yum -y install yum-utils

yum-config-manager --disable mysql80-community

yum-config-manager --enable mysql57-community

3.安装

yum -y install mysql mysql-server

客户端mysql-community-client

服务器端mysql-community-server

初始化:

[root@mysql-rpm ~]# systemctl start mysqld
[root@mysql-rpm ~]# systemctl enable mysqld

修改密码mariadb针对root用户没有初始密码但是mysql针对root用户有初始密码针对mysql在使用之前先修改初始密码

[root@mysql-rpm ~]# mysqladmin -uroot -p'uEe0vMb#kRHY' password 'QianFeng@123'

[root@mysql-rpm ~]# mysql -uroot -pQianFeng@123

(3)源码安装mysql

编译安装数据库

1.准备编译安装的环境

2.获取编译安装包

3.采用cmake的方式配置指定安装目录 存放数据的目录 指定了端口号 指定了字符集等)

4.make进行编译

5.make install 进行安装

初始化:

1.准备用户和组

2.创建了所需要的目录 (在指定的目录下创建)

3.修改安装目录所有者和所属组

4.进行指定用户指定安装目录指定数据存放目录的初始化操作,这一步可以获取到对应的初始密码

5.利用mysqld_safe的命令指定用户后台运行了mysql

6.利用mysqladmin的命令修改了数据库的初始密码

7.登录测试 mysql的命令指定用户和密码  

注意root用在数据库中是数据库的管理员命令注意密码的强度 数字 大小写 特殊字符都要有

扩展:

	编译安装的数据库,每次执行命令都需进入到对应目录下,要么使用绝对路径,直接执行对应的命令

	默认情况下编译安装的数据库不能使用systemctl 来管理mysql的服务如果要用需要自行配置

		[root@xingdian ~]# cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
		[root@xingdian ~]# chkconfig mysqld on

(4)mysql配置、日志文件

/etc/my.cnf默认的数据库mysql的主配置文件

/var/lib/mysql/:用来存放数据的目录

如果在数据库mysql没有运行的情况下删除/var/lib/mysql这个目录下的内容相当于是重置恢复出厂设置当在次启动的时候数据全部被删除了得到了新的初始密码

/var/log/mysqld.log mysql的错误日志文件

编译安装:指定了安装目录和数据存放目录 /usr/local/mysql /usr/local/mysql/data

如果在数据库mysql没有运行的情况下删除了/usr/local/mysql 安装目录相当于卸载了mysql

如果在数据库mysql没有运行的情况下删除了/usr/local/mysql/data 数据存放目录,相当于是重置了数据库

2、数据库操作

create database 库名;

create database 库名 default character set utf8; 指定默认字符集

drop database 库名; 删除库

use 库名; 切换库

show databases; 查看库

select database(); 查看当前库

select user(); 查看登录的用户

创建表名

表名 字段 (数据库类型 【约束条件】)【存储引擎 字符集】

create table t1(name varchar(20),id int(4),sex enum('m','f'),class varchar(50));

整数int 例:年龄 游戏级别 游戏经验

字符串varchar char 例:职位 部门 姓名

枚举enum 例:性别(男女)

浮点数 float 例:身高 体重 薪水

时间和日期类型date/ time/ datetime/ TIMESTAMP/ 例:入学时间 毕业时间

插入insert into 表名 values(字段和值);

mysql>insert into student1 values (1,'xingdian','m',33),(2,'alice','m',20),(3,'jack','m',40); //顺序插入

mysql> insert into student1(name,age) values ('zhuzhu',10),('gougou',20); //只向指定的字段插入值

查询select 字段 from 表名 例://select id,name,sex,age from fxs; //select * from fxs; /查表里所有数据

查看表show tables

查看表结构desc 表名

show create table 表名\G;

show create table 表名

DESCRIBE 表名;

select now();查看当前时间

修改表

alter table 旧表名 rename 新表名 /修改表名字

alter table 表名 add 字段名 数据类型[完整性约束条件..] /增加字段

mysql> alter table student10 add stu_num int not null after name; //添加name字段之后

mysql> alter table student10 add sex enum('male','female') default 'male' first; //添加到最前面

alter table 表名 drop 字段名 //删除字段

alter table 表名 modify 字段名 新数据类型 //修改字段类型(修改表结构)

alter table 表名 modify 字段名 数据类型 [新约束条件] //增加约束

alter table 表名 primary key(数据类型)//增加主键

alter table 表名 modify 带有主键的字段名 数据类型 auto_increment; //修改主键和自增(自增的值为空自动增加)

alter table 表名 modify 字段名 数据类型 约束条件 //删除自增

alter table fxs drop primary key; //删除主键(如果该字段设置自增要优先删除自增)

create table 新表名 select * from 旧表名 //复制表(内容也过来)

create table 新表名 select * from 旧表名 were 1=2; //复制表结构

drop table 表名 //删除表

update 表名 set 列名=值where 条件 //修改数据表中字段的值

mysql> update student set name='123' where id=1;

delete from 表名 where id=1 //删除某一行

mysql> delete from type where id=1;

(1)表约束条件

保证数据的完整性和一致性

PRIMARY KEY (PK) 标识该字段为该表的主键,可以唯一的标识记录,不可以为空 UNIQUE + NOT NULL

FOREIGN KEY (FK) 标识该字段为该表的外键,实现表与表(父表主键/子表1外键/子表2外键之间的关联

NOT NULL 标识该字段不能为空

UNIQUE KEY (UK) 标识该字段的值是唯一的可以为空一个表中可以有多个UNIQUE KEY

AUTO_INCREMENT 标识该字段的值自动增长(整数类型,而且为主键)

DEFAULT 为该字段设置默认值

注意:

是否允许为空默认NULL可设置NOT NULL字段不允许为空必须赋值

字段是否有默认值缺省的默认值是NULL如果插入记录时不给字段赋值此字段使用默认值

例:

MySQL [(none)]> sex enum('male','female') not null default 'male' MySQL [(none)]> age int unsigned NOT NULL default 20 必须为正值(无符号) 不允许为空 默认是20

是否是key 主键 primary key 外键 forengn key

(2)数据类型

整数类型 int 作用用于存储用户的年龄、游戏的Level、经验值等

浮点数类型 float double 作用:用于存储用户的身高、体重、薪水等 //float(5,3) 5宽度 3精度

字符串类型 varchar 作用:用于姓名 长度要求较为高的

枚举类型 enum

时间和日期类型 date time datetime 作用:用于存储用户的注册时间,文章的发布时间,文章的更新时间,员工的入职时间等

3、日志管理

(1)日志分类

错误日志 启动停止关闭失败报错。rpm安装日志位置 /var/log/mysqld.log //在etc数据库的配置文件中

二进制日志实现备份增量备份。只记录改变数据除了select都记

通用查询日志:所有的查询都记下来

中继日志读取主服务器的binlog在本地回放。保持一致

slow log慢查询日志指导调优定义某一个查询语句定义超时时间通过日志提供调优建议给开发人员

Error_log

log-error=/var/log/mysqld.log //默认在/etc/my.cnf倒数第二行

Binary log //binlog日志

log-bin=/var/log/mysql-bin/slave2
server-id=2
root@slave2 ~]# mkdir /var/log/mysql-bin
[root@slave2 ~]# chown mysql.mysql /var/log/mysql-bin/
[root@slave2 ~]# systemctl restart mysqld

查看binlog日志

mysqlbinlog slave2-bin.000001     -v --base64-output=decode-rows

时间点 240507 20:25:38

位置点 # at 4

注:
1. 重启mysqld 会截断
2. flush logs 会截断
3. reset master 删除所有binlog    rm -rf /var/lib/mysql/*.000001
4. 删除部分
PURGE BINARY LOGS TO 'mysql-bin.010';
PURGE BINARY LOGS BEFORE '2019-04-02 22:46:26';

(2)慢查询

/etc/my.cnf

slow_query_log=1
slow_query_log_file=/var/log/mysql-slow/slow.log
long_query_time=3   设置慢查询超时时间  单位是3秒

创建对应目录:

[root@xingdian ~]# mkdir /var/log/mysql-slow
[root@xingdian ~]# chown mysql.mysql mysql-slow

重启服务:

[root@xingdian ~]# systemctl restart mysqld

验证:

[root@xingdian ~]# mysql -uroot -pQianFeng@123
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 2
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> select sleep(6); 
+----------+
| sleep(6) |
+----------+
|        0 |
+----------+
1 row in set (6.00 sec)

mysql> exit
Bye
[root@xingdian ~]# cat /var/log/mysql-slow/slow.log 
/usr/sbin/mysqld, Version: 5.7.39-log (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
# Time: 2022-09-25T06:58:05.496205Z
# User@Host: root[root] @ localhost []  Id:     2
# Query_time: 6.007094  Lock_time: 0.000000 Rows_sent: 1  Rows_examined: 0
SET timestamp=1664089085;
select sleep(6);

4、权限管理

Global level系统级所有库所有表的权限

Database level某个数据库中的所有表的权限

Table level库中的某个表的权限

select * from mysql.user\G //用户的授权信息 全局权限

字段介绍:

用户字段root
权限字段Select_priv
安全字段:*B1DD4ADE47888D9AEC4D705C85230F1B52D2A817

Select_priv查询权限
Insert_priv插入权限
Update_priv更新权限
Delete_priv删除权限
......

select * from mysql.db\G; //针对库的权限

select * from mysql.tables_priv\G; //针对表的权限

(1)用户管理

1.登录和退出

[root@xingdian ~]# mysql -h 192.168.18.160 -P 30042 -u root -pmysql -e "show databases;"
[root@xingdian ~]# mysql -h 192.168.18.160 -P 30042 -u root -pmysql mysql -e "show tables;"

    -h	指定主机名                       【默认为localhost】
    -P	MySQL服务器端口                  【默认3306】
    -u	指定用户名                       【默认root】
    -p	指定登录密码                     【默认为空密码】
	此处mysql为指定登录的数据库 
    -e	接SQL语句  (在脚本中使用)

2.创建用户

grant all on *.* to 'diange'@'localhost' identified by 'QianFeng@123';

注意:

该方式采用授权的方式

ALL 所有权限 select 单独某一个权限(多个权限用逗号隔开)

mysql> grant select on *.* to 'dianye'@'localhost' identified by 'QianFeng@123';
Query OK, 0 rows affected, 1 warning (0.00 sec)
*.*		所有的库所有的表   也可以单独某一个库某一个表
xingdian@localhost  用户有则授权无则创建   localhost % 10.19.40.% 10.19.40.11

3.删除用户

MySQL [(none)]> Drop user xingdian@'%';

4.修改密码

mysqladmin -uroot -p'123' password 'new_password'	    //123为旧密码

5、数据库备份与恢复

(1)tar备份

注意:备份期间,服务不可用

备份过程:完全物理备份

停止数据库

[root@xingdian ~]# systemctl stop mysqld

tar备份数据

[root@xingdian ~]# mkdir /backup
[root@xingdian ~]# cd /var/lib/mysql
[root@xingdian ~]# tar -zcvf /backup/`date +%F`-mysql-all.tar.gz ./*

启动数据库(备份完成后启动数据库,继续为其他服务提供服务)

[root@xingdian ~]# systemctl start mysqld

恢复过程:模拟数据丢失,恢复数据

停止数据库

[root@xingdian ~]# systemctl stop mysqld

清理环境

[root@xingdian ~]# rm -rf /var/lib/mysql/* 

导入备份数据

[root@xingdian ~]# tar -xvf /backup/2019-08-20-mysql-all.tar.gz -C /usr/lib/mysql
[root@xingdian ~]# chown mysql.mysql /var/lib/mysql/* -R

启动数据库(恢复后验证数据是否恢复成功)

[root@xingdian ~]# systemctl start mysqld

(2)xtrabackup备份

1.完整备份

完整备份

创建备份目录:

[root@xingdian ~]# mkdir -p /xtrabackup/full/

备份:

[root@xingdian ~]# innobackupex --user=root --password='QianFeng@123' /xtrabackup/full/

查看备份数据:

[root@xingdian ~]# ls /xtrabackup/full/
2022-09-25_19-40-47

模拟数据丢失数据恢复:(以下操作模拟数据丢失)

丢失前数据库中的数据:

[root@xingdian ~]# mysql -u root -pQianFeng@123
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 7
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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                |
| t1                 |
+--------------------+
5 rows in set (0.00 sec)

数据丢失:

[root@xingdian ~]# systemctl stop mysqld
[root@xingdian ~]# rm -rf /var/lib/mysql/*
[root@xingdian ~]# rm -rf /var/log/mysqld.log 
[root@xingdian ~]# rm -rf /var/log/mysql-slow/slow.log (有则删除,无则不需要操作)

恢复前的验证:

[root@xingdian ~]# innobackupex --apply-log /xtrabackup/full/2022-09-25_19-40-47/

恢复之前需要确认配置文件内有数据库目录指定不然xtrabackup不知道恢复到哪里

[root@xingdian ~]# cat /etc/my.cnf
datadir=/var/lib/mysql

恢复数据:

[root@xingdian ~]# innobackupex --copy-back /xtrabackup/full/2022-09-25_19-40-47/

修改权限:

[root@xingdian ~]# chown  mysql.mysql /var/lib/mysql -R

启动服务:

[root@xingdian ~]# systemctl start mysqld

验证:

[root@xingdian ~]# mysql -u root -pQianFeng@123
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 2
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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                |
| t1                 |
+--------------------+
5 rows in set (0.00 sec)
2.增量备份

增量备份

原理:每次备份上一次备份到现在产生的新数据

注意:在进行增量备份前先进行完整备份

案例:周一进行全备,周二到周天进行增量备份

完整备份:(周一)

[root@xingdian ~]# innobackupex --user=root --password='QianFeng@123' /xtrabackup/full

创建增量备份存放数据目录:

[root@xingdian ~]# mkdir /xtrabackup/zeng -p

模拟数据增加(略)

第一次增量备份:(周二)

[root@xingdian ~]# innobackupex --user=root --password='QianFeng@123' --incremental /xtrabackup/zeng/ --incremental-basedir=/xtrabackup/full/2022-09-25_19-40-47/

第一次增量备份的数据:
[root@xingdian ~]# ls /xtrabackup/zeng/
2022-09-25_19-56-00

模拟数据增加(略)

第二次增量备份:(周三)

[root@xingdian ~]# innobackupex --user=root --password='QianFeng@123' --incremental /xtrabackup/zeng/ --incremental-basedir=/xtrabackup/zeng/2022-09-25_19-56-00/

第二次增量备份的数据:
[root@xingdian ~]# ls /xtrabackup/zeng/
2022-09-25_19-56-00  2022-09-25_19-58-12

后面的增量备份重复上面的操作(略)

增量备份数据恢复流程:(需要模拟数据的丢失)

停止数据库:

[root@xingdian ~]# systemctl stop mysqld

删除数据:

[root@xingdian ~]# rm -rf /var/lib/mysql/*
[root@xingdian ~]# rm -rf /var/log/mysqld.log

其他数据根据实际情况删除

依次重演回滚:

全备回滚:
[root@xingdian ~]# innobackupex --apply-log --redo-only /xtrabackup/full/2022-09-25_19-40-47/

第一次增量回滚:
[root@xingdian ~]# innobackupex --apply-log --redo-only /xtrabackup/full/2022-09-25_19-40-47/ --incremental-dir=/xtrabackup/zeng/2022-09-25_19-56-00/

第二次增量回滚:
[root@xingdian ~]# innobackupex --apply-log --redo-only /xtrabackup/full/2022-09-25_19-40-47/ --incremental-dir=/xtrabackup/zeng/2022-09-25_19-58-12/

根据实际增量备份的次数回滚,可以想恢复到那个时间节点就回滚到那个时间节点,所有的回滚都给全备

恢复数据:

[root@xingdian ~]# innobackupex --copy-back /xtrabackup/full/2022-09-25_19-40-47/

修改权限:

[root@xingdian ~]# chown mysql.mysql /var/lib/mysql -R

启动数据库:

[root@xingdian ~]# systemctl start mysqld

验证:

[root@xingdian ~]# mysql -u root -pQianFeng@123
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 2
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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                |
| t1                 |
| t2                 |
| t3                 |
+--------------------+
3.差异备份

差异备份

原理:只备份跟完整备份不一样的

注意:在进行增量备份前先进行完整备份

案例:周一进行全备,周二到周天进行差异备份

完整备份:(周一)

[root@xingdian ~]# mkdir -p /xtrabackup/full
[root@xingdian ~]# innobackupex --user=root --password=QianFeng@123 /xtrabackup/full

模拟数据增加(略)

第一次差异备份:(周二)

[root@xingdian ~]# mkdir -p /xtrabackup/jian
[root@xingdian ~]# innobackupex --user=root --password=QianFeng@123 --incremental /xtrabackup/jian --incremental-basedir=/xtrabackup/full/2022-09-25_20-10-52/

查看第一次差异备份的数据:
[root@xingdian ~]# ls /xtrabackup/jian/
2022-09-25_20-12-55

模拟数据增加(略)

第二次差异备份:(周三)

[root@xingdian ~]# innobackupex --user=root --password=QianFeng@123 --incremental /xtrabackup/jian --incremental-basedir=/xtrabackup/full/2022-09-25_20-10-52/

查看第二次差异备份的数据:
[root@xingdian ~]# ls /xtrabackup/jian/
2022-09-25_20-12-55  2022-09-25_20-14-32

注意:后面的差异备份跟之前一样,根据需求可以继续差异备份

差异备份恢复流程:(模拟数据丢失)

停止数据库:

[root@xingdian ~]# systemctl stop mysqld

删除数据:

[root@xingdian ~]# rm -rf /var/lib/mysql/*
[root@xingdian ~]# rm -rf /var/log/mysqld.log 

重演数据回滚:

完整备份回滚:
[root@xingdian ~]# innobackupex --apply-log --redo-only /xtrabackup/full/2022-09-25_20-10-52/

差异备份回滚(根据差异备份的原理,如果恢复所有数据只需要将最后依次差异回滚)
[root@xingdian ~]# innobackupex --apply-log --redo-only /xtrabackup/full/2022-09-25_20-10-52/ --incremental-dir=/xtrabackup/jian/2022-09-25_20-14-32/

恢复数据:

[root@xingdian ~]#  innobackupex --copy-back /xtrabackup/full/2022-09-25_20-10-52/

修改权限:

[root@xingdian ~]# chown  mysql.mysql /var/lib/mysql -R

启动数据库:

[root@xingdian ~]# systemctl start  mysqld

数据验证:

[root@xingdian ~]# mysql -u root -pQianFeng@123
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 2
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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 |
| k1                 |
| k2                 |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
9 rows in set (0.00 sec)
4.mysqldump备份

备份表:(前提有库有表)

[root@xingdian ~]# mysqldump -u root -pQianFeng@123 k1 t1 > /t1.sql

恢复表:(恢复之前模拟数据丢失)

[root@xingdian ~]# mysql -u root -pQianFeng@123 k1 < /t1.sql 
mysql: [Warning] Using a password on the command line interface can be insecure.

验证:

[root@xingdian ~]# mysql -u root -pQianFeng@123 -e "use k1;show tables"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------+
| Tables_in_k1 |
+--------------+
| t1           |
+--------------+

备份一个库:

[root@xingdian ~]# mysqldump -u root -pQianFeng@123 k1 > /k1.sql

备份多个库:

[root@xingdian ~]# mysqldump -u root -pQianFeng@123 -B k1 k2 > /kall.sql

备份所有库:

[root@xingdian ~]# mysqldump -u root -pQianFeng@123 -A > /all.sql

数据恢复:

为保证数据一致性,应在恢复数据之前停止数据库对外的服务,停止binlog日志

binlog使用binlog日志恢复数据时也会产生binlog日志如果开启的话需要关闭

mysql> set sql_log_bin=0;
Query OK, 0 rows affected (0.00 sec)

模拟数据丢失(略)

[root@xingdian ~]# mysql -u root -pQianFeng@123 -D k1 < /k1.sql 
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1049 (42000): Unknown database 'k1'
出现该错误是因为在恢复的时候需要有库的存在

[root@xingdian ~]# mysql -u root -pQianFeng@123 -e "create database k1"
[root@xingdian ~]# mysql -u root -pQianFeng@123 -D k1 < /k1.sql 

[root@xingdian ~]# mysql -u root -pQianFeng@123 -e "create database k1"
[root@xingdian ~]# mysql -u root -pQianFeng@123 -e "create database k2"
[root@xingdian ~]# mysql -u root -pQianFeng@123 -D k1 k2 < /kall.sql

或者
mysql> source  /k1.sql

验证:

[root@xingdian ~]# mysql -u root -pQianFeng@123 -e "use k1; show tables;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------+
| Tables_in_k1 |
+--------------+
| t1           |
+--------------+
[root@xingdian ~]# mysql -u root -pQianFeng@123 -e "use k2; show tables;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------+
| Tables_in_k2 |
+--------------+
| t1           |
+--------------+
5.binlog日志备份

原理:日志方法备份恢复数据

日志默认存储位置:

rpm /var/lib/mysql

编译: 安装目录的var下

产生日志:

方式一:编译安装

[root@xingdian ~]# mysqld_safe --log-bin --user=mysql --server-id=1 &

查看binlog日志
[root@xingdian ~]# mysqlbinlog slave2-bin.000001     -v --base64-output=decode-rows
        时间点    141126 14:04:49
        位置点  :     at  106

方式二rpm安装永久

[root@xingdian ~]# vim /etc/my.cnf
log-bin=mylog
server-id=1        //做主从复制使用

[root@xingdian ~]# systemctl restart mysqld

查看:
[root@xingdian ~]# ls /var/lib/mysql
auto.cnf         client-key.pem  ib_logfile1   mysql               private_key.pem  sys
ca-key.pem       ib_buffer_pool  ibtmp1        mysql.sock          public_key.pem   xingdian-bin.index
ca.pem           ibdata1         mylog.000001  mysql.sock.lock     server-cert.pem  xtrabackup_info
client-cert.pem  ib_logfile0     mylog.index

[root@xingdian ~]# mysqlbinlog /var/lib/mysql/mylog.000001 -v --base64-output=decode-rows
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#220925 21:12:47 server id 1  end_log_pos 123 CRC32 0x52358645  Start: binlog v 4, server v 5.7.39-log created 220925 21:12:47 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
# at 123
#220925 21:12:47 server id 1  end_log_pos 154 CRC32 0xa84d8536  Previous-GTIDs
# [empty]
# at 154
#220925 21:13:38 server id 1  end_log_pos 219 CRC32 0xc2b00431  Anonymous_GTID  last_committed=0        sequence_number=1    rbr_only=no
SET @@SESSION.GTID_NEXT= 'ANONYMOUS'/*!*/;
# at 219
#220925 21:13:38 server id 1  end_log_pos 307 CRC32 0x635401a5  Query   thread_id=2     exec_time=0     error_code=0
SET TIMESTAMP=1664111618/*!*/;
SET @@session.pseudo_thread_id=2/*!*/;
SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=1436549152/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\C utf8 *//*!*/;
SET @@session.character_set_client=33,@@session.collation_connection=33,@@session.collation_server=8/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
create database t1
/*!*/;
SET @@SESSION.GTID_NEXT= 'AUTOMATIC' /* added by mysqlbinlog */ /*!*/;
DELIMITER ;
# End of log file
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;

方法二:
mysql>  show binlog events in  "mylog.000001";
+--------------+-----+----------------+-----------+-------------+---------------------------------------+
| Log_name     | Pos | Event_type     | Server_id | End_log_pos | Info                                  |
+--------------+-----+----------------+-----------+-------------+---------------------------------------+
| mylog.000001 |   4 | Format_desc    |         1 |         123 | Server ver: 5.7.39-log, Binlog ver: 4 |
| mylog.000001 | 123 | Previous_gtids |         1 |         154 |                                       |
| mylog.000001 | 154 | Anonymous_Gtid |         1 |         219 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'  |
| mylog.000001 | 219 | Query          |         1 |         307 | create database t1                    |
+--------------+-----+----------------+-----------+-------------+---------------------------------------+
4 rows in set (0.00 sec)

默认查看第一个
mysql>  show binlog events;
+--------------+-----+----------------+-----------+-------------+---------------------------------------+
| Log_name     | Pos | Event_type     | Server_id | End_log_pos | Info                                  |
+--------------+-----+----------------+-----------+-------------+---------------------------------------+
| mylog.000001 |   4 | Format_desc    |         1 |         123 | Server ver: 5.7.39-log, Binlog ver: 4 |
| mylog.000001 | 123 | Previous_gtids |         1 |         154 |                                       |
| mylog.000001 | 154 | Anonymous_Gtid |         1 |         219 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'  |
| mylog.000001 | 219 | Query          |         1 |         307 | create database t1                    |
+--------------+-----+----------------+-----------+-------------+---------------------------------------+
4 rows in set (0.00 sec)

数据恢复:

根据时间点恢复数据:

[root@xingdian ~]# mysqlbinlog --start-datetime='2022-9-25 21:12:47' --stop-datetime='2022-9-25 21:16:55' /var/lib/mysql/mylog.000001  | mysql -u root -pQianFeng@123

根据位置点恢复数据:

mysql>  show binlog events;
+--------------+-----+----------------+-----------+-------------+---------------------------------------+
| Log_name     | Pos | Event_type     | Server_id | End_log_pos | Info                                  |
+--------------+-----+----------------+-----------+-------------+---------------------------------------+
| mylog.000001 |   4 | Format_desc    |         1 |         123 | Server ver: 5.7.39-log, Binlog ver: 4 |
| mylog.000001 | 123 | Previous_gtids |         1 |         154 |                                       |
| mylog.000001 | 154 | Anonymous_Gtid |         1 |         219 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'  |
| mylog.000001 | 219 | Query          |         1 |         307 | create database t1                    |
| mylog.000001 | 307 | Anonymous_Gtid |         1 |         372 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'  |
| mylog.000001 | 372 | Query          |         1 |         453 | drop database t1                      |
| mylog.000001 | 453 | Anonymous_Gtid |         1 |         518 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'  |
| mylog.000001 | 518 | Query          |         1 |         606 | create database t1                    |
| mylog.000001 | 606 | Anonymous_Gtid |         1 |         671 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'  |
| mylog.000001 | 671 | Query          |         1 |         752 | drop database t1                      |
+--------------+-----+----------------+-----------+-------------+---------------------------------------+
[root@xingdian ~]# mysqlbinlog --start-position 219 --stop-position 307 /var/lib/mysql/mylog.000001 | mysql -u root -pQianFeng@123

6、主从复制以及读写分离

1.主从复制概念

什么是主从复制:

主从复制,是用来建立一个和主数据库完全一样的数据库环境,称为从数据库;主数据库一般是准实时的业务数据库

主从复制的作用:

做数据的热备,作为后备数据库,主数据库服务器故障后,可切换到从数据库继续工作,避免数据丢失

架构的扩展业务量越来越大I/O访问频率过高单机无法满足多库的存储降低磁盘I/O访问的频率提高单个机器的I/O性能

读写分离,使数据库能支撑更大的并发

主从复制的原理:

数据库有个bin-log二进制文件记录了所有sql语句

我们的目标就是把主数据库的bin-log文件的sql语句复制到从库

让其在从数据的relay-log(中继日志)重做日志文件中再执行一次这些sql语句即可

总结:

从库slave生成两个线程i/o线程和sql线程i/o将变更记录写到二进制日志文件中再写到中继日志中sql线程读取中继日志解析操作最终数据统一

注意:

I/O进程负责通信

SQL进程负责写数据根据log日志写数据

2.主从复制部署

环境准备

节点 master 192.168.17.194

slave 192.168.17.206

注意:

所有节点关闭防火墙和selinux

保证yum仓库可用

保证网络畅通

如果是克隆的服务器需要修改每台数据库的server-uuid

修改主机名:(所有节点)(可选操作)

[root@xingdian ~]# hostnamectl set-hostname master
[root@xingdian ~]# hostnamectl set-hostname slave

添加本地解析:(所有节点)(可选操作)

[root@master ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.17.194 master
192.168.17.206 slave

[root@slave ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.17.194 master
192.168.17.206 slave
Master部署

安装数据库:(略)

启动数据库:(略)

修改数据库初始密码:(略)

主服务器部署:

[root@master ~]# vi /etc/my.cnf
log-bin = my1log
server-id = 1

创建授权账户:

[root@master ~]# mysql -u root -pQianFeng@123
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 3
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> grant all on *.* to 'slave'@'%' identified by 'QianFeng@123';
mysql> flush privileges;
mysql> exit
Bye

重启服务:

[root@master ~]# systemctl restart mysqld

注意:

replication slave

拥有此权限可以查看从服务器,从主服务器读取二进制日志

super权限

允许用户使用修改全局变量的SET语句以及CHANGE MASTER语句

reload权限

必须拥有reload权限才可以执行flush [tables | logs | privileges]

Slave部署

安装数据库:(略)

启动数据库:(略)

修改数据库初始密码:(略)

从服务器部署:

[root@slave ~]# vi /etc/my.cnf
log-bin = my2log
server-id = 2

重启服务:

[root@slave ~]# systemctl restart mysqld

获取主服务器信息:(主服务器操作)

[root@master ~]# mysql -u root -pQianFeng@123
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 2
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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 binlog events;
+---------------+-----+----------------+-----------+-------------+---------------------------------------+
| Log_name      | Pos | Event_type     | Server_id | End_log_pos | Info                                  |
+---------------+-----+----------------+-----------+-------------+---------------------------------------+
| my1log.000001 |   4 | Format_desc    |         1 |         123 | Server ver: 5.7.39-log, Binlog ver: 4 |
| my1log.000001 | 123 | Previous_gtids |         1 |         154 |                                       |
+---------------+-----+----------------+-----------+-------------+---------------------------------------+
2 rows in set (0.00 sec)

指定主服务器信息:(从服务器操作)

[root@slave ~]# mysql -u root -pQianFeng@123
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 2
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> edit
    -> ;
Query OK, 0 rows affected, 2 warnings (0.01 sec)

注意edit中添加的内容
CHANGE MASTER TO
  MASTER_HOST='master',
  MASTER_USER='slave',  
  MASTER_PASSWORD='QianFeng@123',
  MASTER_PORT=3306,
  MASTER_LOG_FILE='my1log.000001',
  MASTER_LOG_POS=4, 
  MASTER_CONNECT_RETRY=10;  
  
参数解释:
CHANGE MASTER TO
  MASTER_HOST='mysql-master-1.blackmed.cn/ip',  //做过解析的可以直接用主机名没有则用IP
  MASTER_USER='slave',  //主服务器用户
  MASTER_PASSWORD='big', //主服务器的密码
  MASTER_PORT=3306,
  MASTER_LOG_FILE='master2-bin.001', //日志文件
  MASTER_LOG_POS=4, //日志位置
  MASTER_CONNECT_RETRY=10;  //默认尝试次数
获取参数:
mysql> help change master to

启动slave

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

注意:

stop slave停止slave

reset master删除所有的binglog日志文件并将日志索引文件清空重新开始所有新的日志文件用于第一次进行搭建主从库时进行主库binlog初始化工作

reset slave用于删除SLAVE数据库的relaylog日志文件并重新启用新的relaylog文件

查看主从状态:

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: master
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 10
              Master_Log_File: my1log.000001
          Read_Master_Log_Pos: 154
               Relay_Log_File: slave-relay-bin.000002
                Relay_Log_Pos: 361
        Relay_Master_Log_File: my1log.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 568
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 85c6acc4-3db0-11ed-b302-000c29311164
             Master_Info_File: /var/lib/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)

注意:

Slave_IO_Running: Yes

Slave_SQL_Running: Yes

验证:

主服务器创建数据:

mysql> create database t1;
Query OK, 1 row affected (0.00 sec)

从服务器查看数据:

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

7、GTID主从复制

1.GTID概念

GTID基于事务ID复制

GTID全局事务标识global transaction identifiers

是用来代替传统复制的方法GTID复制与普通复制模式的最大不同就是不需要指定二进制文件名和位置

不再使用MASTER_LOG_FILE+MASTER_LOG_POS开启复制。而是使用MASTER_AUTO_POSTION=1的方式开始复制

2.GTID组成

GTID = source_id:transaction_id

source_id源id用于鉴别原服务器即mysql服务器唯一的server_uuid由于GTID会传递到slave所以也可以理解为源ID

transaction_id事务id为当前服务器上已提交事务的一个序列号通常从1开始自增长的序列一个数值对应一个事务

示例:

3E11FA47-71CA-11E1-9E33-C80AA9429562:23

前面的一串为服务器的server_uuid

后面的23为transaction_id

3.GTID工作原理

master更新数据时会在事务前产生GTID一同记录到binlog日志中

slave端的i/o 线程将变更的binlog写入到本地的relay log中

sql线程从relay log中获取GTID然后对比slave端的binlog是否有记录

如果有记录说明该GTID的事务已经执行slave会忽略

如果没有记录slave就会从relay log中执行该GTID的事务并记录到binlog

4.主从部署

注意:实验之前环境初始化,不要有残留的数据

节点 master 10.0.0.128

slave 10.0.042

注意:

所有节点关闭防火墙和selinux

保证yum仓库可用

保证网络畅通

如果是克隆的服务器需要修改每台数据库的server-uuid

修改主机名:(所有节点)(可选操作)

[root@xingdian ~]# hostnamectl set-hostname master
[root@xingdian ~]# hostnamectl set-hostname slave

添加本地解析:(所有节点)(可选操作)

[root@master ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
10.0.0.128 master
10.0.0.42 slave

[root@slave ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
10.0.0.128 master
10.0.0.42 slave
Master部署

安装数据库:(略)

启动数据库:(略)

修改数据库初始密码:(略)

主服务器部署:

[root@master ~]# vim /etc/my.cnf
log-bin
server-id=1
gtid_mode = ON
enforce_gtid_consistency=1

创建授权用户:

[root@master ~]# mysql -u root -pQianFeng@123
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 3
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> grant all on *.* to slave@'%' identified by 'QianFeng@123';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye

重启服务:

[root@master ~]# systemctl restart mysqld
Slave部署

安装数据库:(略)

启动数据库:(略)

修改数据库初始密码:(略)

从服务器部署:

[root@slave ~]# vim /etc/my.cnf
log-bin
server-id=2
gtid_mode = ON
enforce_gtid_consistency=1
relay_log_recovery  = on
master-info-repository=TABLE
relay-log-info-repository=TABLE
//这两个参数会将master.info和relay.info保存在表中默认是Myisam引擎官方建议用

重启服务:

[root@slave ~]# systemctl restart mysqld

配置连接主服务器:

[root@slave ~]# mysql -u root -pQianFeng@123
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 2
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> change master to
    -> master_host='master',
    -> master_user='slave',
    -> master_password='QianFeng@123',
    -> master_auto_position=1;
Query OK, 0 rows affected, 2 warnings (0.00 sec)

启动Slave

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: master
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000001
          Read_Master_Log_Pos: 154
               Relay_Log_File: slave-relay-bin.000002
                Relay_Log_Pos: 369
        Relay_Master_Log_File: master-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 576
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 00813e87-4321-11ed-a33c-000c29311164
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

数据验证:

主服务器创建数据:

[root@master ~]# mysql -u root -pQianFeng@123
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 3
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> create database qfcloud;
Query OK, 1 row affected (0.00 sec)

mysql> exit
Bye

从服务器查验数据:

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

8.GTID双主双从

1.环境准备

注意:

实验之前环境初始化,不要有残留的数据

先做双主M-M互为主从从是双主的从

节点 IP地址
Master-1 10.0.0.128
Master-2 10.0.0.46
Slave-1 10.0.0.42
Slave-2 10.0.0.45

注意:

所有节点关闭防火墙和selinux

保证yum仓库可用

保证网络畅通

如果是克隆的服务器需要修改每台数据库的server-uuid

2.Master-1部署

安装数据库:(略)

启动数据库:(略)

修改数据库初始密码:(略)

主服务器一部署:

[root@master-1 ~]# vim /etc/my.cnf
log-bin = my1log
server-id = 1
gtid_mode=ON
enforce_gtid_consistency=1

创建授权账户:

[root@master-1 ~]# mysql -u root -pQianFeng@123
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 4
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> grant all on *.* to 'slave'@'%' identified by 'QianFeng@123';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye

重启服务:

[root@master-1 ~]# systemctl restart mysqld

3.Master-2部署

安装数据库:(略)

启动数据库:(略)

修改数据库初始密码:(略)

主服务器二部署:

[root@master-2 ~]# vim /etc/my.cnf
log-bin = my2log
server-id = 2 
gtid_mode=ON
enforce_gtid_consistency=1

创建授权账户:

[root@master-2 ~]# mysql -u root -pQianFeng@123
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 4
Server version: 5.7.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> grant all on *.* to 'slave'@'%' identified by 'QianFeng@123';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye

重启服务:

[root@master-2 ~]# systemctl restart mysqld

4.双主互为主从

Master-1

[root@master-1 ~]# mysql  -u root -pQianFeng@123
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 3
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> change master to
    -> master_host='master-2',
    -> master_user='slave',
    -> master_password='QianFeng@123',
    -> master_auto_position=1;
Query OK, 0 rows affected, 2 warnings (0.01 sec)

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: master-2
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: my2log.000001
          Read_Master_Log_Pos: 154
               Relay_Log_File: master-1-relay-bin.000002
                Relay_Log_Pos: 361
        Relay_Master_Log_File: my2log.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 571
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 2
                  Master_UUID: 1b453d94-452e-11ed-b744-000c2936b606
             Master_Info_File: /var/lib/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: 146f4cae-452e-11ed-b87f-000c29311164:1-2
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

mysql> exit
Bye

Master-2

[root@master-2 ~]# mysql -u root -pQianFeng@123
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 3
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> change master to
    -> master_host='master-1',
    -> master_user='slave',
    -> master_password='QianFeng@123',
    -> master_auto_position=1;
Query OK, 0 rows affected, 2 warnings (0.01 sec)

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: master-1
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: my1log.000001
          Read_Master_Log_Pos: 587
               Relay_Log_File: master-2-relay-bin.000002
                Relay_Log_Pos: 794
        Relay_Master_Log_File: my1log.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 587
              Relay_Log_Space: 1004
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 146f4cae-452e-11ed-b87f-000c29311164
             Master_Info_File: /var/lib/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: 146f4cae-452e-11ed-b87f-000c29311164:1-2
            Executed_Gtid_Set: 146f4cae-452e-11ed-b87f-000c29311164:1-2
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

mysql> exit
Bye

5.Slave-1部署

安装数据库:(略)

启动数据库:(略)

修改数据库初始密码:(略)

从服务器一部署:

[root@slave-1 ~]# vim /etc/my.cnf
log-bin = my3log    
server-id = 3
gtid_mode=ON
enforce_gtid_consistency=1
relay_log_info_repository = TABLE
master_info_repository    = TABLE
relay_log_recovery        = on
	当slave从库宕机后假如relay-log损坏了导致一部分中继日志没有处理则自动放弃所有未执行的relay-log并且重新从master上获取日志这样就保证了relay-log的完整性

重启服务:

[root@slave-1 ~]# systemctl restart mysqld

从连接主服务器:

[root@slave-1 ~]# mysql -u root -pQianFeng@123
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 2
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> CHANGE MASTER TO
    -> MASTER_HOST='master-1',
    -> MASTER_USER='slave',
    -> MASTER_PASSWORD='QianFeng@123',
    -> MASTER_AUTO_POSITION=1 FOR CHANNEL 'master-1';
Query OK, 0 rows affected, 2 warnings (0.00 sec)

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: master-1
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: my1log.000001
          Read_Master_Log_Pos: 587
               Relay_Log_File: slave-1-relay-bin-master@002d1.000002
                Relay_Log_Pos: 794
        Relay_Master_Log_File: my1log.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 587
              Relay_Log_Space: 1016
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 146f4cae-452e-11ed-b87f-000c29311164
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 146f4cae-452e-11ed-b87f-000c29311164:1-2
            Executed_Gtid_Set: 146f4cae-452e-11ed-b87f-000c29311164:1-2
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: master-1
           Master_TLS_Version: 
1 row in set (0.00 sec)


mysql> CHANGE MASTER TO
    -> MASTER_HOST='master-2',
    -> MASTER_USER='slave',
    -> MASTER_PASSWORD='QianFeng@123',
    -> MASTER_AUTO_POSITION=1 FOR CHANNEL 'master-2';
Query OK, 0 rows affected, 2 warnings (0.01 sec)

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

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: master-1
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: my1log.000001
          Read_Master_Log_Pos: 587
               Relay_Log_File: slave-1-relay-bin-master@002d1.000002
                Relay_Log_Pos: 794
        Relay_Master_Log_File: my1log.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 587
              Relay_Log_Space: 1016
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 146f4cae-452e-11ed-b87f-000c29311164
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 146f4cae-452e-11ed-b87f-000c29311164:1-2
            Executed_Gtid_Set: 146f4cae-452e-11ed-b87f-000c29311164:1-2
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: master-1
           Master_TLS_Version: 
*************************** 2. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: master-2
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: my2log.000001
          Read_Master_Log_Pos: 154
               Relay_Log_File: slave-1-relay-bin-master@002d2.000002
                Relay_Log_Pos: 361
        Relay_Master_Log_File: my2log.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 583
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 2
                  Master_UUID: 1b453d94-452e-11ed-b744-000c2936b606
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 146f4cae-452e-11ed-b87f-000c29311164:1-2
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: master-2
           Master_TLS_Version: 
2 rows in set (0.00 sec)

6.Slave-2部署

安装数据库:(略)

启动数据库:(略)

修改数据库初始密码:(略)

从服务器二部署:

[root@slave-2 ~]# vim /etc/my.cnf
log-bin = my4log    
server-id = 4
gtid_mode=ON
enforce_gtid_consistency=1
relay_log_info_repository = TABLE
master_info_repository    = TABLE
relay_log_recovery        = on

重启服务:

[root@slave-2 ~]# systemctl restart mysqld

从连接主服务器:

[root@slave-2 ~]# mysql -u root -pQianFeng@123
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 2
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> CHANGE MASTER TO
    -> MASTER_HOST='master-1',
    -> MASTER_USER='slave',
    -> MASTER_PASSWORD='QianFeng@123',
    -> MASTER_AUTO_POSITION=1 FOR CHANNEL 'master-1';
Query OK, 0 rows affected, 2 warnings (0.01 sec)

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

mysql> CHANGE MASTER TO
    -> MASTER_HOST='master-2',
    -> MASTER_USER='slave',
    -> MASTER_PASSWORD='QianFeng@123',
    -> MASTER_AUTO_POSITION=1 FOR CHANNEL 'master-2';
Query OK, 0 rows affected, 2 warnings (0.00 sec)

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

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: master-1
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: my1log.000001
          Read_Master_Log_Pos: 587
               Relay_Log_File: slave-2-relay-bin-master@002d1.000002
                Relay_Log_Pos: 794
        Relay_Master_Log_File: my1log.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 587
              Relay_Log_Space: 1016
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 146f4cae-452e-11ed-b87f-000c29311164
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 146f4cae-452e-11ed-b87f-000c29311164:1-2
            Executed_Gtid_Set: 146f4cae-452e-11ed-b87f-000c29311164:1-2
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: master-1
           Master_TLS_Version: 
*************************** 2. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: master-2
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: my2log.000001
          Read_Master_Log_Pos: 154
               Relay_Log_File: slave-2-relay-bin-master@002d2.000002
                Relay_Log_Pos: 361
        Relay_Master_Log_File: my2log.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 583
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 2
                  Master_UUID: 1b453d94-452e-11ed-b744-000c2936b606
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 146f4cae-452e-11ed-b87f-000c29311164:1-2
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: master-2
           Master_TLS_Version: 
2 rows in set (0.00 sec)

7.验证

主服务器创建数据:

[root@master-1 ~]# mysql  -u root -pQianFeng@123
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: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> create database qfcloud;
Query OK, 1 row affected (0.00 sec)

mysql> exit
Bye

其他服务器验证:

[root@master-2 ~]# mysql -u root -pQianFeng@123
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 8
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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 |
| qfcloud            |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

[root@slave-1 ~]# mysql -u root -pQianFeng@123
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 8
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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 |
| qfcloud            |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

[root@slave-2 ~]# mysql -u root -pQianFeng@123
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 7
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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 |
| qfcloud            |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

9、读写分离

环境介绍

image-20221006131313211

2.读写分离集群部署

A数据库集群部署

单主单从;多主多从等均可

BMycat部署

新机器不需要安装mysql

安装jdk环境

[root@mycat ~]# tar xf jdk-8u211-linux-x64.tar.gz  -C /usr/local/
[root@mycat ~]# mv /usr/local/jdk1.8.0_211/ /usr/local/java

设置环境变量:

[root@mycat ~]# vi /etc/profile
JAVA_HOME=/usr/local/java
PATH=$JAVA_HOME/bin:$PATH
export JAVA_HOME PATH
[root@mycat ~]# source /etc/profile
[root@mycat ~]# java -version
java version "1.8.0_211"
Java(TM) SE Runtime Environment (build 1.8.0_211-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.211-b12, mixed mode)

安装mycat

[root@mycat ~]# tar xf Mycat-server-1.6.7.1-release-20190627191042-linux.tar.gz -C /usr/local/

设置环境变量:

[root@mycat ~]# vi ~/.bash_profile
PATH=$PATH:$HOME/bin:/usr/local/mycat/bin
[root@mycat ~]# source ~/.bash_profile
C数据库部署

Mysql中添加数据库和账户

[root@master-1 ~]# mysql  -u root -pQianFeng@123
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 10
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> create database shop;
Query OK, 1 row affected (0.00 sec)

mysql> create database bbs;
Query OK, 1 row affected (0.00 sec)

mysql> create database blog;
Query OK, 1 row affected (0.00 sec)

mysql> grant all on shop.* to shop@'%' identified by 'QianFeng@123';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> grant all on bbs.* to bbs@'%' identified by 'QianFeng@123';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> grant all on blog.* to blog@'%' identified by 'QianFeng@123';
Query OK, 0 rows affected, 1 warning (0.00 sec)

注意:

创建的库跟mycat关联原则上一个库对应一个项目根据实际情况创建

创建的库需要单独授权用户进行管理,用户名和库名根据实际情况决定

DMycat配置

server.xmlMycat的配置文件设置账号、参数等

[root@mycat conf]# vim server.xml 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mycat:server SYSTEM "server.dtd">
<mycat:server xmlns:mycat="http://io.mycat/">
        <system>
        <property name="nonePasswordLogin">0</property>
        <property name="useHandshakeV10">1</property>
        <property name="useSqlStat">0</property>
        <property name="useGlobleTableCheck">0</property>
                <property name="sequnceHandlerType">2</property>
                <property name="sequnceHandlerPattern">(?:(\s*next\s+value\s+for\s*MYCATSEQ_(\w+))(,|\)|\s)*)+</property>
        <property name="subqueryRelationshipCheck">false</property>
                <property name="processorBufferPoolType">0</property>
                <property name="handleDistributedTransactions">0</property>
                <property name="useOffHeapForMerge">0</property>
        <property name="memoryPageSize">64k</property>
                <property name="spillsFileBufferSize">1k</property>
                <property name="useStreamOutput">0</property>
                <property name="systemReserveMemorySize">384m</property>
                <property name="useZKSwitch">false</property>
                <property name="strictTxIsolation">false</property>
                <property name="useZKSwitch">true</property>
        </system>
        <user name="root" defaultAccount="true">
                <property name="password">123456</property>
                <property name="schemas">TESTDB</property>
        </user>
        <user name="shop">
                <property name="password">123456</property>
                <property name="schemas">shop</property>
        </user>
        <user name="bbs">
                <property name="password">123456</property>
                <property name="schemas">bbs</property>
        </user>
        <user name="blog">
                <property name="password">123456</property>
                <property name="schemas">blog</property>
        </user>
</mycat:server>

注意:

user 用户配置节点
name 登录的用户名也就是连接Mycat的用户名
password 登录的密码也就是连接Mycat的密码
schemas 数据库名这里会和schema.xml中的配置关联多个用逗号分开例如需要这个用户需要管理两个数据库db1,db2则配置db1,db2

schema.xmlMycat对应的物理数据库和数据库表的配置

[root@mycat conf]# cat schema.xml 
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">

        <schema name="shop" checkSQLschema="false" sqlMaxLimit="100" dataNode="dn1"> </schema>
        <schema name="bbs" checkSQLschema="false" sqlMaxLimit="100" dataNode="dn2"> </schema>
        <schema name="blog" checkSQLschema="false" sqlMaxLimit="100" dataNode="dn3"> </schema>
        <dataNode name="dn1" dataHost="localhost1" database="shop" />
        <dataNode name="dn2" dataHost="localhost2" database="bbs" />
        <dataNode name="dn3" dataHost="localhost3" database="blog" />
        <dataHost name="localhost1" maxCon="1000" minCon="10" balance="1"
                          writeType="0" dbType="mysql" dbDriver="native" switchType="1"  slaveThreshold="100">
                <heartbeat>show status like 'wsrep%'</heartbeat>
                <writeHost host="mysql-1" url="mysql-1:3306" user="shop" password="QianFeng@123"> 
                        <readHost host="slave-1" url="slave-1:3306" user="shop" password="QianFeng@123" /> 
                        <readHost host="slave-2" url="slave-2:3306" user="shop" password="QianFeng@123" />           
                </writeHost>
                <writeHost host="mysql-2" url="mysql-2:3306" user="shop" password="QianFeng@123">
                        <readHost host="slave-1" url="slave-1:3306" user="shop" password="QianFeng@123" /> 
                        <readHost host="slave-2" url="slave-2:3306" user="shop" password="QianFeng@123" />  
                </writeHost>         
        </dataHost>
        <dataHost name="localhost2" maxCon="1000" minCon="10" balance="1"
                          writeType="0" dbType="mysql" dbDriver="native" switchType="1"  slaveThreshold="100">
                <heartbeat>show status like 'wsrep%'</heartbeat>
                <writeHost host="mysql-1" url="mysql-1:3306" user="bbs" password="QianFeng@123"> 
                        <readHost host="slave-1" url="slave-1:3306" user="bbs" password="QianFeng@123" /> 
                        <readHost host="slave-2" url="slave-1:3306" user="bbs" password="QianFeng@123" />           
                </writeHost>
                <writeHost host="mysql-2" url="mysql-2:3306" user="bbs" password="QianFeng@123">
                        <readHost host="slave-1" url="slave-1:3306" user="bbs" password="QianFeng@123" /> 
                        <readHost host="slave-2" url="slave-2:3306" user="bbs" password="QianFeng@123" />  
                </writeHost>         
        </dataHost>
        <dataHost name="localhost3" maxCon="1000" minCon="10" balance="1"
                          writeType="0" dbType="mysql" dbDriver="native" switchType="1"  slaveThreshold="100">
                <heartbeat>show status like 'wsrep%'</heartbeat>
                <writeHost host="mysql-1" url="mysql-1:3306" user="blog" password="QianFeng@123"> 
                        <readHost host="slave-1" url="slave-1:3306" user="blog" password="QianFeng@123" /> 
                        <readHost host="slave-2" url="slave-1:3306" user="blog" password="QianFeng@123" />           
                </writeHost>
                <writeHost host="mysql-2" url="mysql-2:3306" user="blog" password="QianFeng@123">
                        <readHost host="slave-1" url="slave-1:3306" user="blog" password="QianFeng@123" /> 
                        <readHost host="slave-2" url="slave-2:3306" user="blog" password="QianFeng@123" />  
                </writeHost>         
        </dataHost>
</mycat:schema>

注意:

balance=1       开启读写分离机制,所有读操作都发送到当前备用的 writeHost 上。
wirteType=0    所有写操作发送到第一个writeHost第一个挂了切换到第二个
switchType=3  基于MySQL Galera cluster的切换机制心跳语句为show status like 'wsrep%'
E启动服务
[root@mycat conf]# mycat start
Starting Mycat-server...
[root@mycat conf]# jps
1494 WrapperSimpleApp
1528 Jps

查看端口:

[root@mycat conf]# ss -antpl
State       Recv-Q Send-Q             Local Address:Port                            Peer Address:Port              
LISTEN      0      128                            *:22                                         *:*                   users:(("sshd",pid=837,fd=3))
LISTEN      0      100                    127.0.0.1:25                                         *:*                   users:(("master",pid=933,fd=13))
LISTEN      0      1                      127.0.0.1:32000                                      *:*                   users:(("java",pid=1494,fd=4))
LISTEN      0      50                            :::37680                                     :::*                   users:(("java",pid=1494,fd=57))
LISTEN      0      128                           :::22                                        :::*                   users:(("sshd",pid=837,fd=4))
LISTEN      0      100                          ::1:25                                        :::*                   users:(("master",pid=933,fd=14))
LISTEN      0      50                            :::1984                                      :::*                   users:(("java",pid=1494,fd=58))
LISTEN      0      100                           :::8066                                      :::*                   users:(("java",pid=1494,fd=79))
LISTEN      0      50                            :::32834                                     :::*                   users:(("java",pid=1494,fd=59))
LISTEN      0      100                           :::9066                                      :::*                   users:(("java",pid=1494,fd=75))
F客户端测试

mycat连接测试

[root@master-1 ~]# mysql -u shop -p123456 -P 8066 -h 10.0.0.47
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 1
Server version: 5.6.29-mycat-1.6.7.1-release-20190627191042 MyCat Server (OpenCloudDB)

Copyright (c) 2000, 2022, 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 |
+----------+
| shop     |
+----------+
1 row in set (0.00 sec)

mysql> use shop
Database changed
mysql> create table t1(id int);
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
+----------------+
| Tables_in_shop |
+----------------+
| t1             |
+----------------+
1 row in set (0.01 sec)

mysql> insert into t1 values(1);
Query OK, 1 row affected (0.03 sec)

mysql> insert into t1 values(2);
Query OK, 1 row affected (0.01 sec)

从服务数据验证:

[root@slave-2 ~]# mysql -u root -pQianFeng@123
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 7
Server version: 5.7.39-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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 |
| qfcloud            |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| bbs                |
| blog               |
| mysql              |
| performance_schema |
| qfcloud            |
| shop               |
| sys                |
+--------------------+
8 rows in set (0.00 sec)

mysql> use shop
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------+
| Tables_in_shop |
+----------------+
| t1             |
+----------------+
1 row in set (0.00 sec)

mysql> select * from t1;
+------+
| id   |
+------+
|    1 |
|    2 |
+------+
2 rows in set (0.00 sec)

3.Mycat配置文件

server.xml
server.xml 配置文件
1.privileges标签
对用户的 schema以及表进行精细化的DML(数据操纵语言)权限控制
<privileges check="false"> </privileges> --check 表示是否开启DML权限检查。默认是关闭。 
--dml 顺序说明insert,update,select,delete 
<schema name="db1" dml="0110" > 
<table name="tb01" dml="0000"></table> 
<table name="tb02" dml="1111"></table> </schema>
db1的权限是update,select。
tb01的权限是啥都不能干。
tb02的权限是insert,update,select,delete。
其他表默认是udpate,select。

2.system标签
这个标签内嵌套的所有 property 标签都与系统配置有关。
<property name="charset">utf8</property> 
字符集
<property name="processors">1</property> 
处理线程数量默认是cpu数量。
<property name="processorBufferChunk">4096</property> 
每次读取留的数量默认4096。
<property name="processorBufferPool">409600</property>
创建共享buffer需要占用的总空间大小。processorBufferChunk*processors*100。
<property name="processorBufferPoolType">0</property>
默认为0。0表示DirectByteBufferPool1表示ByteBufferArena。
<property name="processorBufferLocalPercent">100</property>
二级共享buffer是processorBufferPool的百分比这里设置的是百分比。
<property name="sequnceHandlerType">100</property>
全局ID生成方式。(0:为本地文件方式1:为数据库方式2:为时间戳序列方式3:为ZK生成ID4:为ZK递增ID生成。
<property name="useCompression">1</property>
是否开启mysql压缩协议。1为开启0为关闭默认关闭。
<property name="packetHeaderSize">4</property> 
指定 Mysql 协议中的报文头长度。默认 4。
<property name="maxPacketSize">16M</property>
指定 Mysql 协议可以携带的数据最大长度。默认 16M。
<property name="idleTimeout">1800000</property>
指定连接的空闲超时时间。某连接在发起空闲检查下,发现距离上次使用超过了空闲时间,那么这个连接会被回收,就是被直接的关闭掉。默认 30 分钟,单位毫秒。
<property name="txIsolation">3</property>
前端连接的初始化事务隔离级别,只在初始化的时候使用,后续会根据客户端传递过来的属性对后端数据库连接进行同步。默认为 REPEATED_READ设置值为数字默认 3。 
READ_UNCOMMITTED = 1; 
READ_COMMITTED = 2; 
REPEATED_READ = 3; 
SERIALIZABLE = 4;
<property name="sqlExecuteTimeout">300</property>
SQL 执行超时的时间Mycat 会检查连接上最后一次执行 SQL 的时间,若超过这个时间则会直接关闭这连接。默认时间为 300 秒,单位秒。
<property name="processorCheckPeriod">1000</property>
清理 NIOProcessor 上前后端空闲、超时和关闭连接的间隔时间。默认是 1 秒,单 
位毫秒。
<property name="dataNodeIdleCheckPeriod">300000</property> 
对后端连接进行空闲、超时检查的时间间隔,默认是 300 秒,单位毫秒。
<property name="dataNodeHeartbeatPeriod">10000</property>
对后端所有读、写库发起心跳的间隔时间,默认是 10 秒,单位毫秒。
<property name="bindIp">0.0.0.0</property>
mycat 服务监听的 IP 地址,默认值为 0.0.0.0。
<property name="serverPort">8066</property>
定义 mycat 的使用端口,默认值为 8066。
<property name="managerPort">9066</property>
定义 mycat 的管理端口,默认值为 9066。
<property name="fakeMySQLVersion">5.6</property>
mycat 模拟的 mysql 版本号,默认值为 5.6 版本,如非特需,不要修改这个值,目前支持设置 5.5,5.6,5.7 版本,其他版本可能会有问题。
<property name="useSqlStat">0</property> 
是否开启实时统计。1为开启0为关闭 。
<property name="useGlobleTableCheck">0</property> 
是否开启全局表一致性检测。1为开启0为关闭 。
<property name="handleDistributedTransactions">0</property>
分布式事务开关。0为不过滤分布式事务1为过滤分布式事务2 为不过滤分布式事务,但是记录分布式事务日志。
<property name="maxStringLiteralLength">65535</property>
默认是65535。 64K 用于sql解析时最大文本长度 
以上举例的属性仅仅是一部分,可以配置的变量很多。 
System标签下的属性一般是上线后需要根据实际运行的情况分析后调优的时候进行修改。

3. Firewall标签
防火墙的设置也就是在网络层对请求的地址进行限制主要是从安全角度来保证Mycat不被匿名IP进行访问
<firewall> 
<whitehost>
<host host="127.0.0.1" user="mycat"/>
<host host="127.0.0.2" user="mycat"/>
</whitehost>
<blacklist check="false">
</blacklist>
</firewall>
schema.xml
schema.xml
schema 数据库设置此数据库为逻辑数据库name与server.xml中schema对应
dataNode 分片信息,也就是分库相关配置
dataHost 物理数据库,真正存储数据的数据库

1、schema 标签
<schema name="TESTDB" checkSQLschema="false" sqlMaxLimit="10"> </schema>
schema标签用来定义mycat实例中的逻辑库mycat可以有多个逻辑库每个逻辑库都有自己的相关配置。可以使用schema标签来划分这些不同的逻辑库,如果不配置schema标签所有表的配置会属于同一个默认的逻辑库。逻辑库的概念和MySql的database的概念一样我们在查询两个不同逻辑库中的表的时候需要切换到该逻辑库下进行查询。
name	逻辑数据库名与server.xml中的schema对应
checkSQLschema	数据库前缀相关设置当该值为true时例如我们执行语句select * from TESTDB.company 。mycat会把语句修改为 select * from company 去掉TESTDB。
sqlMaxLimit	当该值设置为某个数值时每条执行的sql语句如果没有加上limit语句Mycat会自动加上对应的值。不写的话默认返回所有的值。需要自己sql语句加limit。

2、dataNode标签
<dataNode name="dn1" dataHost="localhost1" database="db1" />
datanode标签定义了mycat中的数据节点也就是数据分片。一个datanode标签就是一个独立的数据分片。
localhost1数据库实例上的db1物理数据库这就组成一个数据分片最后我们用dn1来标示这个分片。
name 定义数据节点的名字这个名字需要唯一。我们在table标签上用这个名字来建立表与分片对应的关系
dataHost 用于定义该分片属于哪个数据库实例属性与datahost标签上定义的name对应
database 用于定义该分片属于数据库实例上 的具体库。

3、dataHost标签
这个标签直接定义了具体数据库实例,读写分离配置和心跳语句。
<dataHost name="localhost1" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100">
<heartbeat>select user()</heartbeat>
<writeHost host="hostM1" url="192.168.1.100:3306" user="root" password="123456">
<readHost host="hostS1" url="192.168.1.101:3306" user="root" password="123456" />
</writeHost>
</dataHost>

name 唯一标示dataHost标签供上层使用
maxCon 指定每个读写实例连接池的最大连接。
minCon 指定每个读写实例连接池的最小连接,初始化连接池的大小
balance 负载均称类型
balance=“0”不开启读写分离机制所有读操作都发送到当前可用的writeHost上
balance=“1”全部的readHost与stand by writeHost参与select语句的负载均衡简单的说当双主双从模式M1-S1M2-S2 并且M1 M2互为主备正常情况下M2,S1,S2都参与select语句的负载均衡。
balance=“2”所有读操作都随机的在writeHost、readHost上分发
balance=“3”所有读请求随机的分发到writeHst对应的readHost执行writeHost不负担读写压力。
writeType 负载均衡类型。
writeType=“0”, 所有写操作发送到配置的第一个 writeHost第一个挂了切到还生存的第二个writeHost重新启动后已切换后的为准切换记录在配置文件中:dnindex.properties .
writeType=“1”所有写操作都随机的发送到配置的 writeHost。1.5以后版本废弃不推荐。
switchType -1不自动切换
1 默认值 自动切换
2 基于MySql主从同步的状态决定是否切换心跳语句为 show slave status
3 基于mysql galary cluster 的切换机制(适合集群) 心跳语句为 show status like wsrep%
dbType 指定后端链接的数据库类型目前支持二进制的mysql协议还有其他使用jdbc链接的数据库例如mongodboraclespark等
dbDriver 指定连接后段数据库使用的driver目前可选的值有native和JDBC。使用native的话因为这个值执行的是二进制的mysql协议所以可以使用mysql和maridb其他类型的则需要使用JDBC驱动来支持。
如果使用JDBC的话需要符合JDBC4标准的驱动jar 放到mycat\lib目录下并检查驱动jar包中包括如下目录结构文件 META-INF\services\java.sql.Driver。 在这个文件写上具体的driver类名例如com.mysql.jdbc.Driver
writeHost readHost指定后端数据库的相关配置给mycat用于实例化后端连接池。
tempReadHostAvailable 
如果配置了这个属性 writeHost 下面的 readHost 仍旧可用,默认 0 可配置0、1。
1heartbeat标签
这个标签内指明用于和后端数据库进行心跳检查的语句。
例如MYSQL 可以使用 select user()Oracle 可以使用 select 1 from dual 等。
2) writeHost /readHost 标签
这两个标签都指定后端数据库的相关配置用于实例化后端连接池。唯一不同的是writeHost 指定写实例、readHost 指定读实例。
在一个 dataHost 内可以定义多个 writeHost 和 readHost。但是如果 writeHost 指定的后端数据库宕机,那么这个 writeHost 绑定的所有 readHost 都将不可用。
另一方面,由于这个 writeHost 宕机,系统会自动的检测到,并切换到备用的 writeHost 上去。这两个标签的属性相同,这里就一起介绍。
host 用于标识不同实例,一般 writeHost 我们使用M1readHost 我们用S1。
url 后端实例连接地址。Native地址端口 JDBCjdbc的url
password 后端存储实例需要的密码
user 后端存储实例需要的用户名字
weight 权重 配置在 readhost 中作为读节点的权重
usingDecrypt 是否对密码加密默认0。

三.shell

1、初识shell

计算机编程语言

计算机编程语言是程序设计的最重要的工具,它是指计算机能够接受和处理的、具有一定语法规则的语言

阶段:

机器语言

机器语言是用二进制代码表示的、计算机能直接识别和执行的一种机器指令的集合,第一代计算机语言

汇编语言

用与代码指令实际含义相近的英文缩写词、字母和数字等符号来取代指令代码

高级语言

自然语言相近并为计算机所接受和执行的计算机语言称高级语言;独立于机器面向过程或对象的语言

编译型和解释型语言:

解释型

解释性语言编写的程序不进行预先编译,以文本方式存储程序代码

执行时才翻译执行

程序每执行一次就要翻译一遍

代表语言pythonJavaScriptShell等

优缺点:跨平台能力强,易于调,执行速度慢

编译型

编译型语言在执行之前要先经过编译过程,编译成为一个可执行的机器语言的文件

因为翻译只做一遍,以后都不需要翻译,所以执行效率高

典型代表C语言C++

优缺点:执行效率高,缺点是跨平台能力弱,不便调试

(1)shell能做什么

自动化批量系统初始化程序 (update软件安装时区设置安全策略...)

自动化批量软件部署程序 (LAMPLNMPTomcatLVSNginx)

应用管理程序(KVM集群管理扩容MySQLDELLR720批量RAID)

日志分析处理程序(PV, UV, 200, !200, top 100, grep/awk)

自动化备份恢复程序(MySQL完全备份/增量 + Crond)

自动化管理程序(批量远程修改密码,软件升级,配置更新)

自动化信息采集及监控程序(收集系统/应用状态信息CPU,Mem,Disk,Net,TCP Status,Apache,MySQL)

配合Zabbix信息采集(收集系统/应用状态信息CPU,Mem,Disk,Net,TCP Status,Apache,MySQL)

自动化扩容(增加云主机——>业务上线)

Shell可以做任何事(一切取决于业务需求)

(2)shell定义

Shell 是命令解释器,用于与操作系统交互,用来完成各种任务,如文件操作、系统管理、网络管理等

Shell 是一种程序设计语言他有变量有自己的语法结构等shell程序设计语言可以编写功能很强、代码简短的程序

(3)命令和文件自动补齐

下载bash-completion 补全工具

[root@xingdiancloud ~]# yum install bash-completion -y
(4)命令历史记忆功能

上下键调用历史命令

获取历史命令的命令history

获取某一条历史命令:!number 直接执行对应序号的命令

快捷键调用历史命令Ctrl+r 输入关键字调出之前的命令

(5)快捷键

Ctrl+a 切换到命令行开始

Ctrl+e 切换到命令行末尾

Ctrl+u 清除剪切光标之前的内容

Ctrl+k 清除剪切光标之后的内容

Ctrl+y 粘贴刚才锁删除的字符

Ctrl+左右键 快速移动光标

(6)前后台作业控制

&:后台运行

nohup正在运行一个进程退出帐户时该进程不会结束

^C终止

^Z暂停

jobs查看后台进行

bg %工作号:将一个在后台暂停的命令,变成继续执行

fg %工作号:将后台中的命令调至前台继续运行

案例:

[root@xingdiancloud ~]# sleep 1000 &
[1] 7761
[root@xingdiancloud ~]# jobs
[1]+  Running                 sleep 1000 &
[root@xingdiancloud ~]# jobs
[1]+  Running                 sleep 1000 &
[root@xingdiancloud ~]# kill -19 %1

[1]+  Stopped                 sleep 1000
[root@xingdiancloud ~]# jobs
[1]+  Stopped                 sleep 1000
[root@xingdiancloud ~]# bg %1
[1]+ sleep 1000 &
(7)输入输出重定向
0,1,2  > >> 2> 2>> 2>&1 &>        cat < /etc/hosts         cat <<EOF
[root@xingdiancloud ~]# ll /dev/std*
lrwxrwxrwx 1 root root 15 Sep  1  2015 /dev/stderr -> /proc/self/fd/2
lrwxrwxrwx 1 root root 15 Sep  1  2015 /dev/stdin -> /proc/self/fd/0
lrwxrwxrwx 1 root root 15 Sep  1  2015 /dev/stdout -> /proc/self/fd/1
(8)管道
[root@xingdiancloud ~]# ip addr |grep 'inet ' |grep eth0
[root@xingdiancloud ~]# ip addr |grep 'inet ' |tee test |grep eth0	覆盖
[root@xingdiancloud ~]# ip addr |grep 'inet ' |tee -a test |grep eth0	-a 追加
(9)命令排序

; 无论前面是否执行成功,分号后的命令都会继续执行

&& 前面执行成功,后面的才继续执行

|| 前面命令不成功,后面的命令也会继续

[root@xingdiancloud ~]# ./configure && make && make install	(命令返回值 echo $?
[root@xingdiancloud ~]# mkdir /var/111/222/333 && echo ok
[root@xingdiancloud ~]# mkdir -p /var/111/222/333 && echo ok     
[root@xingdiancloud ~]# ls /home/111/222/333/444 || mkdir -p /home/111/222/333/444
(10)shell通配符
  • 匹配任意多个字符 ls in*

? 匹配任意一个字符 ll l?ve

[] 匹配括号中任意一个字符 [a-z]

() 在子shell中执行 (umask 077; touch file1000)

{} 集合 touch file{1..9}

\ 转义符,让元字符回归本意

[root@xingdiancloud ~]# echo *		
[root@xingdiancloud ~]# echo \*
[root@xingdiancloud ~]# touch xing\ dian

2、shell变量

(1)什么是变量

变量来源于数学,是计算机语言中能储存计算结果或能表示值的抽象概念

变量可以通过变量名访问,在指令式语言中,变量通常是可变的;在某些条件下也是不可变的

(2)变量的规则

命名只能使用英文字母,数字和下划线,首个字符不能以数字开头

中间不能有空格,可以使用下划线

不能使用标点符号

不能使用bash里的关键字

(3)变量分类
1.自定义变量

定义变量:变量名=变量值 例如xingdian=123

引用变量:变量名 或变量名或{变量名}

查看变量echo $变量名

取消变量unset 变量名

作用范围仅在当前shell中有效

2.环境变量

定义环境变量:

方法一 export back_dir2=/home/backup

方法二 export back_dir1 将自定义变量转换成环境变量

引用环境变量:变量名 或变量名或{变量名}

查看环境变量echo $变量名

取消环境变量unset 变量名

变量作用范围在当前shell和子shell有效

注意:

环境变量拥有可继承性export之后就拥有继承性

永久生效:写到环境变量脚本,/etc/profile ~/.baserc ~/.bash_profile /etc/bashrc

案例:

[root@xingdiancloud ~]# vim /etc/profile  
JAVA_HOME=/usr/local/java
PATH=$JAVA_HOME/bin:$PATH
export JAVA_HOME PATH
[root@xingdiancloud ~]# vim ~/.bash_profile (只显示部分)
PATH=$PATH:$HOME/bin:/usr/local/mycat/bin

/etc/profile

这是系统最主要的shell设置文件也是用户登陆时系统最先检查的文件有关重要的环境变量都定义在此其中包括PATH,USER,LOGNAME,MAIL,HOSTNAME,HISTSIZE,INPUTRC等。而在文件的最后它会检查并执行/etc/profile.d/*.sh的脚本

~/.bash_profile

这个文件是每位用户的bash环境设置文件它存在与于用户的主目录中当系统执行/etc/profile 后就会接着读取此文件内的设置值。在此文件中会定义USERNAME,BASH_ENV和PATH等环境变量但是此处PATH除了包含系统的$PATH变量外加入用户的“bin”目录路径

~/.bashrc

接下来系统会检查~.bashrc文件这个文件和前两个文件/etc/profile 和~.bash_profile最大的不同是每次执行bash时.bashrc都会被再次读取也就是变量会再次地设置而/etc/profile,./bash_profile只有在登陆时才读取。就是因为要经常的读取所以~/.bashrc文件只定义一些终端机设置以及shell提示符号等功能而不是定义环境变量

~/.bash_login

如果~/.bash_profile文件不存在则系统会转而读取~/.bash_login这个文件内容。这是用户的登陆文件在每次用户登陆系统时bash都会读此内容所以通常都会将登陆后必须执行的命令放在这个文件中

.profile

如果~./bash_profile ~./bash_login两个文件都不存在则会使用这个文件的设置内容其实它的功能与~/.bash_profile相同

.bash_logout

如果想在注销shell前执行一些工作都可以在此文件中设置

[root@xingdiancloud ~]# vi ~.bash_logout
clear
仅执行一个clear命令在你注销的时候

~/.bash_history

这个文件会记录用户先前使用的历史命令

注意:

在/etc/profile.d建立独立的环境变量配置文件

常用环境变量USER UID HOME HOSTNAME PWD PATH

PATH这个变量存放的是所有命令所在的路径 修改PATH=$PATH:+目录

3.位置变量

$1 $2 $3 $4 $5 $6 $7 $8 $9 $10

案例:

[root@xingdiancloud sh]# cat xingdian.sh
#!/bin/bash
echo "hello $1"
[root@xingdiancloud sh]# bash xingdian.sh xingdian
hello xingdian
4.预定义变量
$0    脚本名
$*		所有的参数
$@ 	所有的参数
$# 	参数的个数
$$ 	当前进程的PID
$!     上一个后台进程的PID
$?		上一个命令的返回值 0表示成功

案例:

[root@xingdiancloud sh]# cat test.sh
#!/bin/bash
echo "第2个位置参数是$2"
echo "第1个位置参数是$1"
echo "第4个位置参数是$4"

echo "所有参数是: $*"
echo "所有参数是: $@"
echo "参数的个数是: $#"
echo "当前进程的PID是: $$"

echo '$1='$1
echo '$2='$2
echo '$3='$3
echo '$*='$*
echo '$@='$@
echo '$#='$#
echo '$$='$$