MySQL数据库之Mysql进阶

文章目录

    • 二、Mysql进阶
      • 2.1 多实例
        • 2.1.1 普通方式
        • 2.1.2 mysqld_multi方式
      • 2.2 备份&恢复
        • 2.2.1 备份
        • 2.2.2 恢复
        • 2.2.3 实验
        • 2.2.4 三种备份恢复方法
      • 2.3 主从复制
        • 2.3.1 介绍
        • 2.3.2 应用场景
        • 2.3.3 主从同步原理
        • 2.3.4 配置步骤

二、Mysql进阶

 

2.1 多实例

作用:用于在同一服务器上配置多个mysql服务,监听在不同端口。

 

2.1.1 普通方式

1.创建多实例目录

[root@mysql ~]# mkdir -p /data/mysql/{3307,3308}/data
[root@mysql ~]# chown -R mysql.mysql /data/mysql/
[root@mysql ~]# ll /data/mysql/ -d
drwxr-xr-x 5 mysql mysql 4096 Jul  3 22:01 /data/mysql/

 

2.在不同的实例目录中编辑my.cnf

3307中my.cnf样本

[client]
default-character-set = utf8
port = 3306

[mysqld]
user = mysql
port = 3307
socket = /data/mysql/3307/mysql.sock
basedir = /usr/local/mysql
datadir = /data/mysql/3307/data
log-error = /data/mysql/3307/mysql-error.log
pid-file = /data/mysql/3307/mysql.pid
log_slave_updates = 1
log-bin = /data/mysql/3307/mysql-bin
binlog_format = mixed
binlog_cache_size = 4M
max_binlog_cache_size = 8M
max_binlog_size = 1G
expire_logs_days = 90
key_buffer_size = 384M
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 16M
join_buffer_size = 2M
thread_cache_size = 8
query_cache_size = 32M
query_cache_limit = 2M
query_cache_min_res_unit = 2k
thread_concurrency = 32
#table_cache = 614
#table_open_cache = 512
open_files_limit = 10240
back_log = 600
max_connections = 5000
max_connect_errors = 6000
external-locking = FALSE
max_allowed_packet = 16M
default-storage-engine = MYISAM
thread_stack = 192k
transaction_isolation = READ-COMMITTED
tmp_table_size = 256M
max_heap_table_size = 512M
bulk_insert_buffer_size = 64M
myisam_sort_buffer_size = 64M
myisam_max_sort_file_size = 10G
myisam_repair_threads = 1
myisam_recover
long_query_time = 2
slow_query_log
slow_query_log_file = /data/mysql/3307/slow.log
skip-name-resolve
skip-networking

[mysqldump]
quick
max_allow_packet = 64M

[mysql]
no-auto-rehash
safr-updates
[myisamchk]
key_buffer_size = 256M
sort_buffer_size = 256M
read_buffer = 2M

[mysqldump]
quick
max_allow_packet = 64M
[mysql]
no-auto-rehash
safe-updates

[myisamchk]
key_buffer_size = 256M
sort_buffer_size = 256M
read_buffer = 2M
write_buffer = 2M
[mysqlhotcopy]
interactive-timeout

3307参照3306的my.cnf

[mysqld]
user = mysql
port = 3308
socket = /data/mysql/3308/mysql.sock
basedir = /usr/local/mysql
datadir = /data/mysql/3308/data
log-error = /data/mysql/3308/mysql-error.log
pid-file = /data/mysql/3308/mysql.pid
log_slave_updates = 1
log-bin = /data/mysql/3308/mysql-bin

 

3.初始化数据文件

[root@mysql ~]# /usr/local/mysql/bin/mysqld --defaults-file=/data/mysql/3307/3307my.cnf --initialize --user=mysql
[root@mysql ~]# /usr/local/mysql/bin/mysqld --defaults-file=/data/mysql/3308/3308my.cnf --initialize --user=mysql

 

4.启动mysql多实例

[root@mysql ~]# /usr/local/mysql/bin/mysqld_safe --defaults-file=/data/mysql/3307/3307my.cnf > /dev/null 2>&1 &
[root@mysql ~]# /usr/local/mysql/bin/mysqld_safe --defaults-file=/data/mysql/3308/3308my.cnf > /dev/null 2>&1 &

 
去找密码

[root@mysql ~]# tail /data/mysql/3307/mysql-error.log 
2020-07-04T03:12:03.935537Z 0 [System] [MY-013169] [Server] /usr/local/mysql/bin/mysqld (mysqld 8.0.20) initializing of server in progress as process 3702
2020-07-04T03:12:03.950285Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2020-07-04T03:12:07.211213Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2020-07-04T03:12:10.132323Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: Sue/%%cT>0.D

 

5.登录到mysql多实例

[root@mysql ~]# /usr/local/mysql/bin/mysql -uroot -p -S /data/mysql/3307/mysql.sock
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.20

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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> SET PASSWORD FOR root@localhost ='123';
Query OK, 0 rows affected (0.01 sec)


[root@mysql ~]# /usr/local/mysql/bin/mysql -uroot -p -S /data/mysql/3308/mysql.sock
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.20

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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> SET PASSWORD FOR root@localhost ='123';
Query OK, 0 rows affected (0.01 sec)

 

6.关闭mysql多实例

 mysqladmin -u root -p -S /data/mysql/3307/mysql.sock shutdown
 mysqladmin -u root -p -S /data/mysql/3308/mysql.sock shutdown

 
 

2.1.2 mysqld_multi方式

mysqld_multi多实例脚本部署:https://www.cnblogs.com/01-single/p/9051412.html

#!/bin/bash
set -e
#定义mysql_multi多实例数据的配置,如需增加,在后面函数对应地方需要增加
mydir=/data/mysql_multi
#mysql sock
my1=mysql3307
my2=mysql3308
#mysql_multi name
mycnf1=mysqld3307
mycnf2=mysqld3308
#mysql port
my1_port=3307
my2_port=3308
#需要安装机器的内网IP
nei_eth=192.168.0.131
#mysql size
pool_size=2048M

#######################分割线,以上内容需要按需修改######################

pack="mysql-5.6.35.tar.gz"
pack_dir="mysql-5.6.35"
conf_file="/usr/local/mysql"

if [ ! -f ${pack} ]
then
    echo "没有找到mysql安装包"
    exit 1
fi

if [ -e /usr/local/mysql* ] || ps -ef | /bin/grep -Ev "$(basename $0)|grep" | /bin/grep -q mysql  
then
    echo "本机可能已安装有mysql,请检查确认!"
    exit 2
fi

if /bin/grep  mysql /etc/passwd || /bin/grep  mysql /etc/group
then
    echo "已存在mysql账户或用户组"
else
    groupadd mysql
    useradd -r -s /sbin/nologin -g mysql mysql
fi

yum remove mysql*
yum -y install  bison-devel ncurses-devel autoconf

tar xf ${pack} \
&& cd ${pack_dir} \
&& echo "configuring..." \
&& cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/usr/local/mysql/data -DSYSCONFDIR=/etc -DWITH_MYISAM_STORAGE_ENGINE=1 -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_MEMORY_STORAGE_ENGINE=1 -DWITH_READLINE=1 -DMYSQL_UNIX_ADDR=/tmp/mysql.sock -DMYSQL_TCP_PORT=3306 -DENABLED_LOCAL_INFILE=1 -DWITH_PARTITION_STORAGE_ENGINE=1 -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci  >> /opt/make_mysql.txt \
&& echo "making..." \
&& make -j `grep processor /proc/cpuinfo | wc -l` >> /opt/make_mysql.txt \
&& echo "installing..." \
&& make install >> /opt/make_mysql.txt  

if [ "$?" == 0 ];then
    echo "程序安装成功,即将配置并启动" 
else
    echo "mysql安装失败" 
    exit 1
fi

rm -f /opt/make_mysql.txt

chown -R mysql:mysql ${conf_file}
cd ${conf_file}
scripts/mysql_install_db --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --user=mysql
[ -f /etc/my.cnf ] && mv /etc/my.cnf /etc/my.cnf.bak
cp support-files/mysql.server /etc/init.d/mysql
echo "export PATH=$PATH:/usr/local/mysql/bin" >> /etc/profile
source /etc/profile
systemctl enable mysql
systemctl start mysql && echo "OK mysql启动成功"  || echo "lost mysql启动失败"

#配置mysql_multi函数
install_mysql_multi() {
    mkdir -p $mydir/{$my1,$my2}/{mydata,log}
    chown -R mysql:mysql $mydir/{$my1,$my2}
    cd ${conf_file}
    scripts/mysql_install_db --basedir=${conf_file} --datadir=$mydir/$my1/mydata --user=mysql
    scripts/mysql_install_db --basedir=${conf_file} --datadir=$mydir/$my2/mydata --user=mysql

    touch $mydir/{$my1,$my2}/log/log-err.err
    chown -R mysql:mysql $mydir/{$my1,$my2}/log/log-err.err
cat >${conf_file}/my.cnf<

 
 

2.2 备份&恢复

2.2.1 备份

mysqldump

语法:mysqldump -u root -p 数据库名 [表名]… > 文件路径

mysqldump的工作原理

  • mysqldump备份数据的过程,实际上就是把数据库从mysql库里以sql语句的形式直接输出并保存成文件的过程

  • 备份的文件/* 到 */都是注释
    使用egrep -v “^(#|–|/*)” FILE过滤注释

选项

  • -A 备份所有数据库 mysqldump -u root -p -A -B -F --events
  • -B DBNAME... #能接多个库,并添加创建库和切换库的语句(使用-B备份的sql文件恢复时不需要指定库,也不用手动创建库)
  • -F 切割binlog
  • --master-data=1 #1:执行从库从主库某位置的binlog恢复 ,2注释执行语句
  • -x #锁表
  • -d DBNAME #只备份表结构
  • --compact #输出内容减少,用于调试
  • --no-create-info|-t #只备份数据
  • --single-transaction # 适合innodb事务数据库备份

 

实例

备份并压缩

mysqldump -u root -p -B DBNAME | gzip > xxx.gz

实例

[root@mysql ~]# /usr/local/mysql/bin/mysqldump -uroot -p -B haha | gzip > haha.gz
Enter password: 
[root@mysql ~]# ls
anaconda-ks.cfg          test2.sql			download                 test.sql		haha.gz

备份多个库

mysqldump -u root -p -B DBNAME1 DBNAME2 | gzip > FILE

分库备份 通过shell脚本

两种不同引擎的备份

myisam

mysql -u root -p -A -B --master-data=2 -x --events --flush-privileges  | gzip > /tmp/xx.sql

innodb

mysql -u root -p -A -B --master-data=2 --single-transaction --events  --flush-privileges | gzip > /tmp/xx.sql

 
 

2.2.2 恢复

1.binlog日志
功能
mysql的二进制日志文件,默认存放在mysql数据目录下
用来记录mysql内部增删改等对数据库有更新内容的记录

启用binlog功能
修改my.cnf中的[mysqld]
log-bin=FILENAME

mysqlbinlog
查看binlog日志
选项
-d DB #只导出指定库sql语句,默认binlog会保存所有库的操作

实例
使用binlog恢复数据库

mysqlbinlog  mysql-bin.00001 > 1.sql
mysql -u root -p DBNAME < 1.sql

基于指定位置恢复

mysqlbinlog mysql-bin.00001 --start-position=106  > xx.sql
mysql  < xx.sql
mysqlbinlog mysql-bin.00001 --stop-position=500
mysqlbinlog mysql-bin.00001 --start-position=106 --stop-position=500

基于指定时间恢复

mysqlbinlog --start-datetime="2017-10-17 16:52:06" mysql-bin.000001
mysqlbinlog --stop-datetime="2017-10-17 16:52:06" /var/lib/mysql/mysql-bin.000001
mysqlbinlog --start-datetime="2017-10-17 16:52:06" --stop-datetime="2017-10-18 16:52:06" mysql-bin.000001

2.利用mysql中的source命令恢复
3.使用mysql命令恢复

mysql -uroot -p student < /var/backup/student_bak.sql

 
 

2.2.3 实验

1.开启3307实例的binlog日志

[root@mysql ~]# /usr/local/mysql/bin/mysql -uroot -p -S /data/mysql/3307/mysql.sock
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.20 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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 variables like '%log_bin%';
+---------------------------------+----------------------------------+
| Variable_name                   | Value                            |
+---------------------------------+----------------------------------+
| log_bin                         | ON                               |
| log_bin_basename                | /data/mysql/3307/mysql-bin       |
| log_bin_index                   | /data/mysql/3307/mysql-bin.index |
| log_bin_trust_function_creators | OFF                              |
| log_bin_use_v1_row_events       | OFF                              |
| sql_log_bin                     | ON                               |
+---------------------------------+----------------------------------+
6 rows in set (1.15 sec)

2.在3307的实例上创建pldb,并建表插入数据(n个用户)

mysql> create database pldb;
Query OK, 1 row affected (0.17 sec)
mysql> use pldb
Database changed
mysql> create table student(id int(4) not null,name char(20) not null,age tinyint(2) not null default '0',dept varchar(16) default null);
Query OK, 0 rows affected, 2 warnings (3.80 sec)

mysql> insert into student values(1,'alice',20,'CS'),(2,'bob',22,'CS'),(3,'haha',20,'MATH'),(4,'hehe',21,'ENG'),(5,'lihua',20,'CS'),(6,'xiaohong',20,'CS');
Query OK, 6 rows affected (0.72 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> select * from student;
+----+----------+-----+------+
| id | name     | age | dept |
+----+----------+-----+------+
|  1 | alice    |  20 | CS   |
|  2 | bob      |  22 | CS   |
|  3 | haha     |  20 | MATH |
|  4 | hehe     |  21 | ENG  |
|  5 | lihua    |  20 | CS   |
|  6 | xiaohong |  20 | CS   |
+----+----------+-----+------+
6 rows in set (0.00 sec)

3.备份pldb数据库的数据(–master-data=2)

[root@mysql ~]# /usr/local/mysql/bin/mysqldump -u root -p pldb --master-data=2 --single-transaction --events  --flush-privileges -P 3307 -S /data/mysql/3307/mysql.sock > /tmp/pldb.sql

4.3307实例新数据写入数据库(插入新数据)

mysql> select * from student;
+----+----------+-----+------+
| id | name     | age | dept |
+----+----------+-----+------+
|  1 | alice    |  20 | CS   |
|  2 | bob      |  22 | CS   |
|  3 | haha     |  20 | MATH |
|  4 | hehe     |  21 | ENG  |
|  5 | lihua    |  20 | CS   |
|  6 | xiaohong |  20 | CS   |
|  7 | pupu     |   8 | CS   |
|  8 | chaoyang |  14 | CS   |
+----+----------+-----+------+
8 rows in set (0.01 sec)

mysql> insert into student values(9,'yanliang',14,'CS'),(10,'fanghao',14,'CS');
Query OK, 2 rows affected (0.03 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from student;
+----+----------+-----+------+
| id | name     | age | dept |
+----+----------+-----+------+
|  1 | alice    |  20 | CS   |
|  2 | bob      |  22 | CS   |
|  3 | haha     |  20 | MATH |
|  4 | hehe     |  21 | ENG  |
|  5 | lihua    |  20 | CS   |
|  6 | xiaohong |  20 | CS   |
|  7 | pupu     |   8 | CS   |
|  8 | chaoyang |  14 | CS   |
|  9 | yanliang |  14 | CS   |
| 10 | fanghao  |  14 | CS   |
+----+----------+-----+------+
10 rows in set (0.00 sec)

5.将所有pldb数据库的数据恢复到3308实例中

在3308创建一个数据库

mysql> create database student3308;
Query OK, 1 row affected (1.03 sec)

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

回复数据到3308

[root@mysql ~]# /usr/local/mysql/bin/mysql -uroot -p -S /data/mysql/3308/mysql.sock student3308 < /tmp/pldb.sql 
Enter password: 

进去查看 发现只有之前插入的数据,备份完后插入的数据不在

mysql> use student3308
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_student3308 |
+-----------------------+
| student               |
+-----------------------+
1 row in set (0.06 sec)

mysql> select * from student;
+----+----------+-----+------+
| id | name     | age | dept |
+----+----------+-----+------+
|  1 | alice    |  20 | CS   |
|  2 | bob      |  22 | CS   |
|  3 | haha     |  20 | MATH |
|  4 | hehe     |  21 | ENG  |
|  5 | lihua    |  20 | CS   |
|  6 | xiaohong |  20 | CS   |
|  7 | pupu     |   8 | CS   |
|  8 | chaoyang |  14 | CS   |
+----+----------+-----+------+
8 rows in set (0.00 sec)

 
 

为什么呢:http://www.linuxmysql.com/14/2018/898.htm

深入理解–single-transaction:https://blog.csdn.net/bigtree_3721/article/details/76730325

1、对于支持事务的引擎如InnoDB,参数上是在备份的时候加上–single-transaction保证数据一致性

--single-transaction实际上通过做了下面两个操作:

①在开始的时候把该session的事务隔离级别设置成repeatable read;

②然后启动一个事务(执行bigin),备份结束的时候结束该事务(执行commit)

有了这两个操作,在备份过程中,该session读到的数据都是启动备份时的数据(同一个点)。可以理解为对于innodb引擎来说加了该参数,备份开始时就已经把要备份的数据定下来了,备份过程中的提交的事务时是看不到的,也不会备份进去。

2、对于不支持事务的引擎如MyISAM,只能通过锁表来保证数据一致性,这里分三种情况:

①导出全库:加–lock-all-tables参数,这会在备份开始的时候启动一个全局读锁(执行flush tables with read lock),其他session可以读取但不能更新数据,备份过程中数据没有变化,所以最终得到的数据肯定是完全一致的;

②导出单个库:加–lock-tables参数,这会在备份开始的时候锁该库的所有表,其他session可以读但不能更新该库的所有表,该库的数据一致;

③导出单个表:加–lock-tables参数,这会在备份开始的时候锁该表,其他表不受影响,该表数据一致。

 
 

2.2.4 三种备份恢复方法

1)备份恢复策略

1.要定期做 mysql 备份,并考虑系统可以承受的恢复时间。

2.确保 mysql 打开 log-bin,有了 binarylog,mysql 才可以在必要的时候做完整恢

复,或基于时间点的恢复,或基于位置的恢复。

3.要经常做备份恢复测试,确保备份是有效的,并且是可以恢复的。

2)冷备份

备份:

1.停掉 mysql 服务,在操作系统级别备份 mysql 的数据文件。

2.重启 mysql 服务,备份重启以后生成的 binlog。

恢复:

1.停掉 mysql 服务,在操作系统级别恢复 mysql 的数据文件。

2.重启 mysql 服务,使用 mysqlbinlog 恢复自备份以来的 binlog。

3)逻辑备份

备份:

1.选择在系统空闲时,比如在夜间,使用 mysqldump –F(flush-logs)备份数据库。

mysqldump –u root –p*** pointcard –F > pointcard.sql

2.并备份 mysqldump 开始以后生成的 binlog。

恢复:

1.停掉应用,执行 mysql 导入备份文件.

mysql –u root –p*** pointcard < pointcard.sql

2.使用 mysqlbinlog 恢复自 mysqldump 备份以来的 binlog。

mysqlbinlog $HOME/data/mysql-bin.123456 | mysql -u root –p***

4)备份工具ibbackup

使用方法:

编辑用于启动的配置文件my.cnf和用于备份的配置文件my2.cnf

my.cnf的例子如下:

[mysqld]
datadir = /home/alice/data
innodb_data_home_dir = /home/alice/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /home/alice/data
set-variable = innodb_log_files_in_group=2
set-variable = innodb_log_file_size=20M

如果想备份到/home/alice/backup,则my2.cnf的例子如下:

[mysqld]
datadir = /home/alice/backup
innodb_data_home_dir = /home/alice/backup
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /home/alice/backup
set-variable = innodb_log_files_in_group=2
set-variable = innodb_log_file_size=20M

开始备份

ibbackup my.cnf my2.cnf

如果需要恢复,则进行日志重做

ibbackup --apply-log my2.cnf

恢复后重启数据库服务

./bin/mysqld_saft --defaults-file=my2.cnf &

 
 

2.3 主从复制

2.3.1 介绍

mysql支持单向,双向,链式级联,在主从复制中,一台服务器充当主服务器master,而一个或多个充当从服务器slave,复制的过程是异步的(即有时延的)

各种主从复制逻辑图

  • 单向主从

MySQL数据库之Mysql进阶_第1张图片

  • 双向主从(不推荐)

MySQL数据库之Mysql进阶_第2张图片

  • 一主多从

MySQL数据库之Mysql进阶_第3张图片

  • 线性链式级联

MySQL数据库之Mysql进阶_第4张图片

 
 

2.3.2 应用场景

1.主从互为备份
当主服务器出现问题,我们可以人工/自动的切换到从服务器让其继续提供服务

2.读写分离
主从服务器可以通过程序(php,java等)或代理软件(mysql-proxy,amoeba)对用户对数据库的请求实现读写分离。从库一般只处理select查询请求,来降低用户查询的等待时间及缓解主服务器的压力,对于更新的请求则交给主服务器处理,并且要确保数据实时主从同步

3.根据业务拆分从库
根据业务的不同讲从库拆分为不同的部分,比如从1-3用于帖子浏览,从4用于后台访问,从5用于binlog备份

 
 

2.3.3 主从同步原理

MySQL数据库之Mysql进阶_第5张图片

注意事项
主库必须开启binlog功能
主从server-id 唯一

 
 

2.3.4 配置步骤

1.master开启binlog

[root@mysql ~]# vim /data/mysql/3307/3307my.cnf 
[mysqld]
log_bin=/data/mysql/3307/mysql-bin
server-id=100

3308同理开启日志

并添加

server-id=101

2.创建用户用于主从复制

mysql> use mysql
mysql> CREATE USER 'master'@'192.168.217.153' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.25 sec)
mysql> GRANT REPLICATION SLAVE ON *.* TO [email protected];
Query OK, 0 rows affected (0.17 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000003 |     4410 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
mysql> show grants for [email protected];
+--------------------------------------------------------------+
| Grants for [email protected]                            |
+--------------------------------------------------------------+
| GRANT REPLICATION SLAVE ON *.* TO `master`@`192.168.217.153` |
+--------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> show master logs;
+------------------+-----------+-----------+
| Log_name         | File_size | Encrypted |
+------------------+-----------+-----------+
| mysql-bin.000003 |      4410 | No        |
+------------------+-----------+-----------+
1 row in set (0.00 sec)

3.主库全量备份

[root@mysql ~]# mysqldump -uroot -p -S /data/mysql/3307/mysql.sock -B pldb > /tmp/pldb_bak.sql

4.从库做全量恢复

[root@mysql ~]# mysql -u root -p -S /data/mysql/3308/mysql.sock < /tmp/pldb_bak.sql 
Enter password:

5.从库设定主库信息

mysql> CHANGE MASTER TO MASTER_HOST='192.168.217.153' , MASTER_PORT=3307,MASTER_USER='master' ,MASTER_PASSWORD='123' ,MASTER_LOG_FILE='mysql-bin.000003' ,MASTER_LOG_POS=4410,get_master_public_key=1;
Query OK, 0 rows affected, 2 warnings (0.03 sec)

6.从库开启主从复制

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

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.217.153
                  Master_User: master
                  Master_Port: 3307
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000003
          Read_Master_Log_Pos: 4410
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 324
        Relay_Master_Log_File: mysql-bin.000003
             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: 4410
              Relay_Log_Space: 533
              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: 25ed5ffb-bda4-11ea-9987-000c297df451
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
       Master_public_key_path: 
        Get_master_public_key: 1
            Network_Namespace: 
1 row in set (0.00 sec)

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

7.测试

在主服务器Mysql,建立数据库,并在这个库中建表插入一条数据

mysql> use pldb
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> create table tt(id int(4) not null,name char(20) not null);
Query OK, 0 rows affected, 1 warning (0.70 sec)

mysql> insert into tt values(1,'haha'),(2,'hehe');
Query OK, 2 rows affected (0.16 sec)
Records: 2  Duplicates: 0  Warnings: 0

在从服务器Mysql查询

mysql> use pldb
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_pldb |
+----------------+
| grade          |
| student        |
| tt             |
+----------------+
3 rows in set (0.00 sec)
mysql> select * from tt;
+----+------+
| id | name |
+----+------+
|  1 | haha |
|  2 | hehe |
+----+------+
2 rows in set (0.00 sec)

你可能感兴趣的:(#,Linux之mysql)