翼度科技»论坛 编程开发 mysql 查看内容

MySQL8.4一主一从环境搭建实现

9

主题

9

帖子

27

积分

新手上路

Rank: 1

积分
27
一、MySQL数据库服务环境搭建


1.1、下载及上传mysql二进制安装包

下载地址
MySQL :: Download MySQL Community Server

上传mysql-8.4.0-linux-glibc2.17-x86_64.tar.xz到soft目录
  1. ls -lsa /soft
复制代码
1.2、增加MySQL用户组及用户
  1. groupadd mysql
  2. useradd -r -s /bin/false -g mysql mysql

  3. mkdir -p /mysql/data/3306/data
  4. mkdir -p /mysql/backup/backup-db

  5. chown -R mysql:mysql /mysql
复制代码
1.3、编辑配置文件my.cnf

vi /mysql/data/3306/my.cnf
  1. [mysqld]
  2. server-id=573306
  3. port=3306
  4. basedir=/mysql/app/mysql
  5. datadir=/mysql/data/3306/data
  6. log-error=/mysql/log/3306/superdb-error.log
  7. socket=/mysql/data/3306/mysql.sock
  8. pid-file=/mysql/data/3306/mysql.pid
  9. character-set-server=utf8mb4
  10. lower_case_table_names=1
  11. innodb_log_file_size=1G
  12. default-storage-engine=INNODB
  13. mysql_native_password=on
  14. secure_file_priv=''
复制代码
  1. [mysql]
  2. prompt=(\\u@\\h)[\\d]>\\_

  3. [client]
  4. port=3306
  5. default-character-set=utf8mb4
复制代码
1.4、解压
  1. cd /soft
  2. ls
  3. xz -d mysql-8.4.0-linux-glibc2.17-x86_64.tar.xz
  4. tar xvf mysql-8.4.0-linux-glibc2.17-x86_64.tar
  5. mv mysql-8.4.0-linux-glibc2.17-x86_64 /mysql/app/mysql
复制代码
1.5、mysql初始化
  1. /mysql/app/mysql/bin/mysqld  --defaults-file=/mysql/data/3306/my.cnf  --initialize --user=mysql --basedir=/mysql/app/mysql --datadir=/mysql/data/3306/data
复制代码
1.6、安全模式启动mysql
  1. /mysql/app/mysql/bin/mysqld_safe --defaults-file=/mysql/data/3306/my.cnf  &
复制代码
1.7、设置软连接sock软连接
  1. ln -sf /mysql/data/3306/mysql.sock /tmp/mysql.sock
复制代码
1.8、编辑环境变量mysql home目录及登陆提示

vi ~/.bash_profile
  1. PATH=$PATH:/mysql/app/mysql/bin:$HOME/bin
  2. export MYSQL_PS1="(\u@\h:\p)[\d]>"
复制代码
source ~/.bash_profile
  1. tail -fn300 /mysql/log/3306/superdb-error.log
复制代码
1.9、登陆mysql设置密码
  1. defaultmysqlpwd=`grep 'A temporary password' /mysql/log/3306/superdb-error.log |awk -F "root@localhost: " '{ print $2}' |tail -n1`
  2. mysql -uroot -p"${defaultmysqlpwd}" --connect-expired-password <<EOF
  3. ALTER USER 'root'@'localhost' IDENTIFIED BY 'Root@2024';
  4. EOF
  5. sleep 1

  6. mysql -uroot -p

  7. create user 'root'@'%' identified  by 'Root@2024';
  8. grant all privileges on *.* to 'root'@'%';
  9. flush privileges;
  10. exit
复制代码
1.10、设置service mysqld 服务

mv /mysql/app/mysql/support-files/mysql.server /mysql/app/mysql/support-files/mysql.server.bak
vi /mysql/app/mysql/support-files/mysql.server
  1. #!/bin/sh
  2. # Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
  3. # This file is public domain and comes with NO WARRANTY of any kind

  4. # MySQL daemon start/stop script.

  5. # Usually this is put in /etc/init.d (at least on machines SYSV R4 based
  6. # systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql.
  7. # When this is done the mysql server will be started when the machine is
  8. # started and shut down when the systems goes down.

  9. # Comments to support chkconfig on RedHat Linux
  10. # chkconfig: 2345 64 36
  11. # description: A very fast and reliable SQL database engine.

  12. # Comments to support LSB init script conventions
  13. ### BEGIN INIT INFO
  14. # Provides: mysql
  15. # Required-Start: $local_fs $network $remote_fs
  16. # Should-Start: ypbind nscd ldap ntpd xntpd
  17. # Required-Stop: $local_fs $network $remote_fs
  18. # Default-Start:  2 3 4 5
  19. # Default-Stop: 0 1 6
  20. # Short-Description: start and stop MySQL
  21. # Description: MySQL is a very fast and reliable SQL database engine.
  22. ### END INIT INFO

  23. # If you install MySQL on some other places than /usr/local/mysql, then you
  24. # have to do one of the following things for this script to work:
  25. #
  26. # - Run this script from within the MySQL installation directory
  27. # - Create a /etc/my.cnf file with the following information:
  28. #   [mysqld]
  29. #   basedir=<path-to-mysql-installation-directory>
  30. # - Add the above to any other configuration file (for example ~/.my.ini)
  31. #   and copy my_print_defaults to /usr/bin
  32. # - Add the path to the mysql-installation-directory to the basedir variable
  33. #   below.
  34. #
  35. # If you want to affect other MySQL variables, you should make your changes
  36. # in the /etc/my.cnf, ~/.my.cnf or other MySQL configuration files.

  37. # If you change base dir, you must also change datadir. These may get
  38. # overwritten by settings in the MySQL configuration files.

  39. basedir=/mysql/app/mysql
  40. datadir=/mysql/data/3306/data

  41. # Default value, in seconds, afterwhich the script should timeout waiting
  42. # for server start.
  43. # Value here is overriden by value in my.cnf.
  44. # 0 means don't wait at all
  45. # Negative numbers mean to wait indefinitely
  46. service_startup_timeout=900

  47. # Lock directory for RedHat / SuSE.
  48. lockdir='/var/lock/subsys'
  49. lock_file_path="$lockdir/mysql"

  50. # The following variables are only set for letting mysql.server find things.

  51. # Set some defaults
  52. mysqld_pid_file_path=/mysql/data/3306/mysql.pid
  53. if test -z "$basedir"
  54. then
  55.   basedir=/mysql/app/mysql
  56.   bindir=/mysql/app/mysql/bin
  57.   if test -z "$datadir"
  58.   then
  59.     datadir=/mysql/data/3306/data
  60.   fi
  61.   sbindir=/mysql/app/mysql/bin
  62.   libexecdir=/mysql/app/mysql/bin
  63. else
  64.   bindir="$basedir/bin"
  65.   if test -z "$datadir"
  66.   then
  67.     datadir="/mysql/app/3306/data"
  68.   fi
  69.   sbindir="$basedir/sbin"
  70.   libexecdir="$basedir/libexec"
  71. fi

  72. # datadir_set is used to determine if datadir was set (and so should be
  73. # *not* set inside of the --basedir= handler.)
  74. datadir_set=

  75. #
  76. # Use LSB init script functions for printing messages, if possible
  77. #
  78. lsb_functions="/lib/lsb/init-functions"
  79. if test -f $lsb_functions ; then
  80.   . $lsb_functions
  81. else
  82.   log_success_msg()
  83.   {
  84.     echo " SUCCESS! $@"
  85.   }
  86.   log_failure_msg()
  87.   {
  88.     echo " ERROR! $@"
  89.   }
  90. fi

  91. PATH="/sbin:/usr/sbin:/bin:/mysql/app/mysql/bin:/usr/bin:$basedir/bin"
  92. export PATH

  93. mode=$1    # start or stop

  94. [ $# -ge 1 ] && shift


  95. other_args="$*"   # uncommon, but needed when called from an RPM upgrade action
  96.            # Expected: "--skip-networking --skip-grant-tables"
  97.            # They are not checked here, intentionally, as it is the resposibility
  98.            # of the "spec" file author to give correct arguments only.

  99. case `echo "testing\c"`,`echo -n testing` in
  100.     *c*,-n*) echo_n=   echo_c=     ;;
  101.     *c*,*)   echo_n=-n echo_c=     ;;
  102.     *)       echo_n=   echo_c='\c' ;;
  103. esac

  104. parse_server_arguments() {
  105.   for arg do
  106.     case "$arg" in
  107.       --basedir=*)  basedir=`echo "$arg" | sed -e 's/^[^=]*=//'`
  108.                     bindir="$basedir/bin"
  109.                     if test -z "$datadir_set"; then
  110.                       datadir="$basedir/data"
  111.                     fi
  112.                     sbindir="$basedir/sbin"
  113.                     libexecdir="$basedir/libexec"
  114.         ;;
  115.       --datadir=*)  datadir=`echo "$arg" | sed -e 's/^[^=]*=//'`
  116.                     datadir_set=1
  117.         ;;
  118.       --pid-file=*) mysqld_pid_file_path=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
  119.       --service-startup-timeout=*) service_startup_timeout=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
  120.     esac
  121.   done
  122. }

  123. wait_for_pid () {
  124.   verb="$1"           # created | removed
  125.   pid="$2"            # process ID of the program operating on the pid-file
  126.   pid_file_path="$3" # path to the PID file.

  127.   i=0
  128.   avoid_race_condition="by checking again"

  129.   while test $i -ne $service_startup_timeout ; do

  130.     case "$verb" in
  131.       'created')
  132.         # wait for a PID-file to pop into existence.
  133.         test -s "$pid_file_path" && i='' && break
  134.         ;;
  135.       'removed')
  136.         # wait for this PID-file to disappear
  137.         test ! -s "$pid_file_path" && i='' && break
  138.         ;;
  139.       *)
  140.         echo "wait_for_pid () usage: wait_for_pid created|removed pid pid_file_path"
  141.         exit 1
  142.         ;;
  143.     esac

  144.     # if server isn't running, then pid-file will never be updated
  145.     if test -n "$pid"; then
  146.       if kill -0 "$pid" 2>/dev/null; then
  147.         :  # the server still runs
  148.       else
  149.         # The server may have exited between the last pid-file check and now.  
  150.         if test -n "$avoid_race_condition"; then
  151.           avoid_race_condition=""
  152.           continue  # Check again.
  153.         fi

  154.         # there's nothing that will affect the file.
  155.         log_failure_msg "The server quit without updating PID file ($pid_file_path)."
  156.         return 1  # not waiting any more.
  157.       fi
  158.     fi

  159.     echo $echo_n ".$echo_c"
  160.     i=`expr $i + 1`
  161.     sleep 1

  162.   done

  163.   if test -z "$i" ; then
  164.     log_success_msg
  165.     return 0
  166.   else
  167.     log_failure_msg
  168.     return 1
  169.   fi
  170. }

  171. # Get arguments from the my.cnf file,
  172. # the only group, which is read from now on is [mysqld]
  173. if test -x "$bindir/my_print_defaults";  then
  174.   print_defaults="$bindir/my_print_defaults"
  175. else
  176.   # Try to find basedir in /etc/my.cnf
  177.   conf=/mysql/data/3306/my.cnf
  178.   print_defaults=
  179.   if test -r $conf
  180.   then
  181.     subpat='^[^=]*basedir[^=]*=\(.*\)$'
  182.     dirs=`sed -e "/$subpat/!d" -e 's//\1/' $conf`
  183.     for d in $dirs
  184.     do
  185.       d=`echo $d | sed -e 's/[         ]//g'`
  186.       if test -x "$d/bin/my_print_defaults"
  187.       then
  188.         print_defaults="$d/bin/my_print_defaults"
  189.         break
  190.       fi
  191.     done
  192.   fi

  193.   # Hope it's in the PATH ... but I doubt it
  194.   test -z "$print_defaults" && print_defaults="my_print_defaults"
  195. fi

  196. #
  197. # Read defaults file from 'basedir'.   If there is no defaults file there
  198. # check if it's in the old (depricated) place (datadir) and read it from there
  199. #

  200. extra_args=""
  201. if test -r "/mysql/data/3306/my.cnf"
  202. then
  203.   extra_args="-e /mysql/data/3306/my.cnf"
  204. fi

  205. parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server`

  206. #
  207. # Set pid file if not given
  208. #
  209. if test -z "$mysqld_pid_file_path"
  210. then
  211.   mysqld_pid_file_path=$datadir/`hostname`.pid
  212. else
  213.   case "$mysqld_pid_file_path" in
  214.     /* ) ;;
  215.     * )  mysqld_pid_file_path="$datadir/$mysqld_pid_file_path" ;;
  216.   esac
  217. fi

  218. case "$mode" in
  219.   'start')
  220.     # Start daemon

  221.     # Safeguard (relative paths, core dumps..)
  222.     cd $basedir

  223.     echo $echo_n "Starting MySQL"
  224.     if test -x $bindir/mysqld_safe
  225.     then
  226.       # Give extra arguments to mysqld with the my.cnf file. This script
  227.       # may be overwritten at next upgrade.
  228.       $bindir/mysqld_safe --defaults-file=/mysql/data/3306/my.cnf --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null &
  229.       wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

  230.       # Make lock for RedHat / SuSE
  231.       if test -w "$lockdir"
  232.       then
  233.         touch "$lock_file_path"
  234.       fi

  235.       exit $return_value
  236.     else
  237.       log_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)"
  238.     fi
  239.     ;;

  240.   'stop')
  241.     # Stop daemon. We use a signal here to avoid having to know the
  242.     # root password.

  243.     if test -s "$mysqld_pid_file_path"
  244.     then
  245.       # signal mysqld_safe that it needs to stop
  246.       touch "$mysqld_pid_file_path.shutdown"

  247.       mysqld_pid=`cat "$mysqld_pid_file_path"`

  248.       if (kill -0 $mysqld_pid 2>/dev/null)
  249.       then
  250.         echo $echo_n "Shutting down MySQL"
  251.         kill $mysqld_pid
  252.         # mysqld should remove the pid file when it exits, so wait for it.
  253.         wait_for_pid removed "$mysqld_pid" "$mysqld_pid_file_path"; return_value=$?
  254.       else
  255.         log_failure_msg "MySQL server process #$mysqld_pid is not running!"
  256.         rm "$mysqld_pid_file_path"
  257.       fi

  258.       # Delete lock for RedHat / SuSE
  259.       if test -f "$lock_file_path"
  260.       then
  261.         rm -f "$lock_file_path"
  262.       fi
  263.       exit $return_value
  264.     else
  265.       log_failure_msg "MySQL server PID file could not be found!"
  266.     fi
  267.     ;;

  268.   'restart')
  269.     # Stop the service and regardless of whether it was
  270.     # running or not, start it again.
  271.     if $0 stop  $other_args; then
  272.       $0 start $other_args
  273.     else
  274.       log_failure_msg "Failed to stop running server, so refusing to try to start."
  275.       exit 1
  276.     fi
  277.     ;;

  278.   'reload'|'force-reload')
  279.     if test -s "$mysqld_pid_file_path" ; then
  280.       read mysqld_pid <  "$mysqld_pid_file_path"
  281.       kill -HUP $mysqld_pid && log_success_msg "Reloading service MySQL"
  282.       touch "$mysqld_pid_file_path"
  283.     else
  284.       log_failure_msg "MySQL PID file could not be found!"
  285.       exit 1
  286.     fi
  287.     ;;
  288.   'status')
  289.     # First, check to see if pid file exists
  290.     if test -s "$mysqld_pid_file_path" ; then
  291.       read mysqld_pid < "$mysqld_pid_file_path"
  292.       if kill -0 $mysqld_pid 2>/dev/null ; then
  293.         log_success_msg "MySQL running ($mysqld_pid)"
  294.         exit 0
  295.       else
  296.         log_failure_msg "MySQL is not running, but PID file exists"
  297.         exit 1
  298.       fi
  299.     else
  300.       # Try to find appropriate mysqld process
  301.       mysqld_pid=`pidof $libexecdir/mysqld`

  302.       # test if multiple pids exist
  303.       pid_count=`echo $mysqld_pid | wc -w`
  304.       if test $pid_count -gt 1 ; then
  305.         log_failure_msg "Multiple MySQL running but PID file could not be found ($mysqld_pid)"
  306.         exit 5
  307.       elif test -z $mysqld_pid ; then
  308.         if test -f "$lock_file_path" ; then
  309.           log_failure_msg "MySQL is not running, but lock file ($lock_file_path) exists"
  310.           exit 2
  311.         fi
  312.         log_failure_msg "MySQL is not running"
  313.         exit 3
  314.       else
  315.         log_failure_msg "MySQL is running but PID file could not be found"
  316.         exit 4
  317.       fi
  318.     fi
  319.     ;;
  320.     *)
  321.       # usage
  322.       basename=`basename "$0"`
  323.       echo "Usage: $basename  {start|stop|restart|reload|force-reload|status}  [ MySQL server options ]"
  324.       exit 1
  325.     ;;
  326. esac

  327. exit 0
复制代码
cp /mysql/app/mysql/support-files/mysql.server /etc/init.d/mysqld
chmod 775 /etc/init.d/mysqld
  1. chkconfig --list
  2. chkconfig --add mysqld
  3. chkconfig --list
复制代码
service mysqld status
service mysqld stop
service mysqld start

二、数据准备,模拟生产的环境


2.1、主节点创建库及测试表
  1. create database db01;
  2. use db01;

  3. create table dept
  4. ( deptno int unsigned auto_increment primary key comment '部门编号',
  5. dname  varchar(15) comment '部门名称'  ,
  6. loc  varchar(50) comment '部门所在位置'
  7. )engine = innodb default charset=utf8mb4 comment='员工部门表';

  8. create table emp(
  9. empno int unsigned auto_increment primary key comment '雇员编号',
  10. ename varchar(15)  comment '雇员姓名' ,
  11. job varchar(10)   comment '雇员职位'  ,
  12. mgr int unsigned  comment '雇员对应的领导的编号',
  13. hiredate  date    comment '雇员的雇佣日期' ,
  14. sal decimal(7,2)  comment '雇员的基本工资' ,
  15. comm  decimal(7,2)   comment '奖金'  ,
  16. deptno int unsigned   comment '所在部门' ,
  17. foreign key(deptno) references dept(deptno)
  18. )engine = innodb default charset =utf8mb4 comment='雇员信息表';

  19. create table salgrade
  20. (
  21. grade int comment '工资等级',
  22. losal int comment '此等级的最低工资',
  23. hisal int comment '此等级的最高工资'
  24. )engine=innodb default charset=utf8mb4 comment='工资等级表';

  25. alter table salgrade add constraint pk_salgrade_primary primary key (grade,losal,hisal);

  26. create table bonus
  27. (   ename  varchar(10) comment '雇员姓名',
  28. job    varchar(9) comment '雇员职位',
  29. sal    decimal(7,2) comment '雇员工资',
  30. comm   decimal(7,2) comment '雇员奖金'
  31. )engine=innodb default charset=utf8mb4 comment='雇员奖金表' ;

  32. alter table bonus add constraint pk_bonus_primary primary key (ename,job);

  33. show full columns from emp;
  34. select * from information_schema.tables where table_schema='db01' and table_name='emp';
  35. select * from information_schema.columns where table_schema='db01' and table_name='emp';

  36. insert into dept values (10,'ACCOUNTING','NEW YORK');
  37. insert into dept values (20,'RESEARCH','DALLAS');
  38. insert into dept values (30,'SALES','CHICAGO');
  39. insert into dept values (40,'OPERATIONS','BOSTON');

  40. insert into emp values    (7369,'SMITH','CLERK',7902,'1980-12-17',800,null,20);
  41. insert into emp values    (7499,'ALLEN','SALESMAN',7698,'1981-2-20',1600,300,30);
  42. insert into emp values    (7521,'WARD','SALESMAN',7698,'1981-2-22',1250,500,30);
  43. insert into emp values    (7566,'JONES','MANAGER',7839,'1981-4-2',2975,null,20);
  44. insert into emp values    (7654,'MARTIN','SALESMAN',7698,'1981-9-28',1250,1400,30);
  45. insert into emp values    (7698,'BLAKE','MANAGER',7839,'1981-5-1',2850,null,30);
  46. insert into emp values    (7782,'CLARK','MANAGER',7839,'1981-6-9',2450,null,10);
  47. insert into emp values    (7788,'SCOTT','ANALYST',7566,'87-7-13',3000,null,20);
  48. insert into emp values    (7839,'KING','PRESIDENT',null,'1981-11-17',5000,null,10);
  49. insert into emp values    (7844,'TURNER','SALESMAN',7698,'1981-9-8',1500,0,30);
  50. insert into emp values    (7876,'ADAMS','CLERK',7788,'87-7-13',1100,null,20);
  51. insert into emp values    (7900,'JAMES','CLERK',7698,'1981-12-3',950,null,30);
  52. insert into emp values    (7902,'FORD','ANALYST',7566,'1981-12-3',3000,null,20);
  53. insert into emp values    (7934,'MILLER','CLERK',7782,'1982-1-23',1300,null,10);

  54. insert into salgrade values (1,700,1200);
  55. insert into salgrade values (2,1201,1400);
  56. insert into salgrade values (3,1401,2000);
  57. insert into salgrade values (4,2001,3000);
  58. insert into salgrade values (5,3001,9999);
  59. commit;
复制代码
三、搭建主从及测试


3.1、设置复制源配置
  1. show variables like '%server_id%';
复制代码
3.2、为复制创建用户

注意:主从节点都执行,方便后期主从切换
  1. CREATE USER 'repl'@'%' identified by 'Root@3306';
  2. GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';
复制代码
测试从库连接主库
  1. mysql -u repl -p -h 192.168.80.50
复制代码
3.3、获取复制源的二进制日志位置

在主节点的不同会话中,使用 SHOW BINARY LOG STATUS语句确定当前二进制日志文件名和位置:
  1. SHOW BINARY LOG STATUS;
复制代码
  1. (root@localhost:mysql.sock)[(none)]>SHOW BINARY LOG STATUS;
  2. +---------------+----------+--------------+------------------+-------------------+
  3. | File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
  4. +---------------+----------+--------------+------------------+-------------------+
  5. | binlog.000001 |    11518 |              |                  |                   |
  6. +---------------+----------+--------------+------------------+-------------------+
  7. 1 row in set (0.00 sec)
复制代码
3.4、主节点备份及上传到备节点

使用mysqldump工具创建要复制的所有数据库的转储。这是推荐的方法,尤其是在使用 InnoDB.
mysqldump --all-databases --master-data > dbdump.db
如果不使用 --master-data,则需要手动锁定单独会话中的所有表 --ignore-table使用选项 排除数据库中的所有表 --databases选项仅命名要转储的那些数据库
  1. cd /mysql/backup/backup-db
  2. mysqldump  -uroot  -p  --all-databases  --master-data=1 > dbfulldump.db
复制代码
du -sh dbfulldump.db
从节点检查目录是的否存在
  1. mkdir -p /mysql/backup/backup-db
复制代码
拷贝主节点的备份到从节点
  1. scp -r /mysql/backup/backup-db/dbfulldump.db root@192.168.80.51:/mysql/backup/backup-db
复制代码
3.5、设置副本


3.5.1、调整server_id
  1. show variables like '%server%';
  2. +---------------------------------+--------------------------------------+
  3. | Variable_name                   | Value                                |
  4. +---------------------------------+--------------------------------------+
  5. | character_set_server            | utf8mb4                              |
  6. | collation_server                | utf8mb4_0900_ai_ci                   |
  7. | immediate_server_version        | 999999                               |
  8. | innodb_dedicated_server         | OFF                                  |
  9. | innodb_ft_server_stopword_table |                                      |
  10. | original_server_version         | 999999                               |
  11. | server_id                       | 513306                               |
  12. | server_id_bits                  | 32                                   |
  13. | server_uuid                     | 81c80be9-10d4-11ef-b4df-000c290e14ee |
  14. +---------------------------------+--------------------------------------+
  15. 9 rows in set (0.00 sec)
复制代码
3.5.2、导入数据
  1. show databases;
  2. +--------------------+
  3. | Database           |
  4. +--------------------+
  5. | information_schema |
  6. | mysql              |
  7. | performance_schema |
  8. | sys                |
  9. +--------------------+
  10. 4 rows in set (0.00 sec)
复制代码
source dbdump.db

3.5.3、配置连接到主服务器的相关信息
  1. CHANGE REPLICATION SOURCE TO SOURCE_HOST='192.168.80.50', SOURCE_LOG_FILE='binlog.000001', SOURCE_LOG_POS=11518, SOURCE_PORT=3306, SOURCE_USER='repl', SOURCE_PASSWORD='Root@3306';
复制代码
3.5.4、启动从服务器的复制线程
  1. start REPLICA;
复制代码
3.6、验证
  1. show REPLICA status \G
  2. show processlist \G
  3. select * from db01.emp;
  4. select * from db01.dept;
复制代码
3.7、在线启用 GTID 事务


3.7.1、主库
  1. SET @@GLOBAL.ENFORCE_GTID_CONSISTENCY = WARN;
  2. SET @@GLOBAL.ENFORCE_GTID_CONSISTENCY = ON;
  3. SET @@GLOBAL.GTID_MODE = OFF_PERMISSIVE;
  4. SET @@GLOBAL.GTID_MODE = ON_PERMISSIVE;
  5. SHOW STATUS LIKE 'ONGOING_ANONYMOUS_TRANSACTION_COUNT';
  6. SET @@GLOBAL.GTID_MODE = ON;
复制代码
3.7.2、从库
  1. SET @@GLOBAL.ENFORCE_GTID_CONSISTENCY = WARN;
  2. SET @@GLOBAL.ENFORCE_GTID_CONSISTENCY = ON;
  3. SET @@GLOBAL.GTID_MODE = OFF_PERMISSIVE;
  4. SET @@GLOBAL.GTID_MODE = ON_PERMISSIVE;
  5. SHOW STATUS LIKE 'ONGOING_ANONYMOUS_TRANSACTION_COUNT';
  6. SET @@GLOBAL.GTID_MODE = ON;stop replica;CHANGE REPLICATION SOURCE TO SOURCE_AUTO_POSITION = 1 ;START replica;
复制代码
3.7.3、修改配置文件
  1. gtid_mode = ON
  2. enforce_gtid_consistency = ON
复制代码
3.7.4、主节点模拟增量数据产生及数据同步
  1. CREATE TABLE t_city_list(
  2. id bigint auto_increment,
  3. country VARCHAR(64),
  4. city VARCHAR(64),
  5. constraint pk_t_city_list_id primary key(id)
  6. );

  7. INSERT INTO t_city_list(country,city) VALUES ('中国','北京');
  8. INSERT INTO t_city_list(country,city) VALUES ('中国','广州');
  9. INSERT INTO t_city_list(country,city) VALUES ('中国','深圳');
  10. INSERT INTO t_city_list(country,city) VALUES ('中国','香港');
  11. INSERT INTO t_city_list(country,city) VALUES ('中国','上海');
  12. INSERT INTO t_city_list(country,city) VALUES ('日本','东京');
  13. INSERT INTO t_city_list(country,city) VALUES ('日本','大阪');
  14. commit;

  15. select * from db01.t_city_list
复制代码
从节点检查
  1. select * from t_city_list;
复制代码
主节点再次新增数据
  1. INSERT INTO t_city_list(country,city) VALUES ('中国','中山');
  2. INSERT INTO t_city_list(country,city) VALUES ('中国','珠海');
复制代码
从节点再次检查数据同步情况
  1. select * from t_city_list;
复制代码
3.8、主备切换


3.8.1、设置主库只读
  1. set global read_only=ON;
  2. set global super_read_only=ON;
复制代码
3.8.2、查看从库进程状态
  1. show replica status \G;
复制代码
确认参数项
Slave_IO_Running              参数值为YES
Slave_SQL_Running           参数值为YES
Seconds_Behind_Master    参数值为   0

3.8.3、主备节点两边的executed_gtid集合对比
  1. select @@global.gtid_executed;
  2. +-------------------------------------------+
  3. | @@global.gtid_executed                    |
  4. +-------------------------------------------+
  5. | e9adc552-10d5-11ef-81ba-000c2940f616:1-10 |
  6. +-------------------------------------------+
  7. 1 row in set (0.00 sec)

  8. show global variables like 'gtid_%';
  9. +----------------------------------+-------------------------------------------+
  10. | Variable_name                    | Value                                     |
  11. +----------------------------------+-------------------------------------------+
  12. | gtid_executed                    | e9adc552-10d5-11ef-81ba-000c2940f616:1-10 |
  13. | gtid_executed_compression_period | 0                                         |
  14. | gtid_mode                        | ON                                        |
  15. | gtid_owned                       |                                           |
  16. | gtid_purged                      |                                           |
  17. +----------------------------------+-------------------------------------------+
  18. 5 rows in set (0.00 sec)
复制代码
3.8.4、从库停掉复制进程并清空主从信息(原从库)
  1. stop replica;
  2. reset replica all;
复制代码
3.8.5、从库关闭只读(原从库)
  1. set global read_only=off;
  2. set global super_read_only=off;
复制代码
3.8.6、主库设置执行原主库转为从库
  1. CHANGE MASTER TO MASTER_HOST='192.168.80.51',MASTER_PORT=3306, MASTER_USER='repl', MASTER_PASSWORD='Root@3306',master_auto_position=1; #mysql5.7/mysql8.0

  2. CHANGE REPLICATION SOURCE TO SOURCE_HOST='192.168.80.51',SOURCE_PORT=3306,SOURCE_USER='repl', SOURCE_PASSWORD='Root@3306',SOURCE_auto_position=1; #mysql8.4

  3. start replica;
复制代码
3.8.7、检查验证

新从节点原主节点80.50
  1. show replica status \G;
复制代码
新主节点原从节点80.51
  1. INSERT INTO db01.t_city_list(country,city) VALUES ('中国','兰州');
复制代码
新主从节点检查数据同步情况
  1. select * from db01.t_city_list;
复制代码
到此这篇关于MySQL8.4一主一从环境搭建实现的文章就介绍到这了,更多相关MySQL8.4一主一从搭建内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/database/322179krk.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具