一、mysql数据库服务环境搭建
1.1、下载及上传mysql二进制安装包
下载地址
mysql :: download mysql community server
上传mysql-8.4.0-linux-glibc2.17-x86_64.tar.xz到soft目录
ls -lsa /soft
1.2、增加mysql用户组及用户
groupadd mysql useradd -r -s /bin/false -g mysql mysql mkdir -p /mysql/data/3306/data mkdir -p /mysql/backup/backup-db chown -r mysql:mysql /mysql
1.3、编辑配置文件my.cnf
vi /mysql/data/3306/my.cnf
[mysqld] server-id=573306 port=3306 basedir=/mysql/app/mysql datadir=/mysql/data/3306/data log-error=/mysql/log/3306/superdb-error.log socket=/mysql/data/3306/mysql.sock pid-file=/mysql/data/3306/mysql.pid character-set-server=utf8mb4 lower_case_table_names=1 innodb_log_file_size=1g default-storage-engine=innodb mysql_native_password=on secure_file_priv=''
[mysql] prompt=(\\u@\\h)[\\d]>\\_ [client] port=3306 default-character-set=utf8mb4
1.4、解压
cd /soft ls xz -d mysql-8.4.0-linux-glibc2.17-x86_64.tar.xz tar xvf mysql-8.4.0-linux-glibc2.17-x86_64.tar mv mysql-8.4.0-linux-glibc2.17-x86_64 /mysql/app/mysql
1.5、mysql初始化
/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
/mysql/app/mysql/bin/mysqld_safe --defaults-file=/mysql/data/3306/my.cnf &
1.7、设置软连接sock软连接
ln -sf /mysql/data/3306/mysql.sock /tmp/mysql.sock
1.8、编辑环境变量mysql home目录及登陆提示
vi ~/.bash_profile
path=$path:/mysql/app/mysql/bin:$home/bin export mysql_ps1="(\u@\h:\p)[\d]>"
source ~/.bash_profile
tail -fn300 /mysql/log/3306/superdb-error.log
1.9、登陆mysql设置密码
defaultmysqlpwd=`grep 'a temporary password' /mysql/log/3306/superdb-error.log |awk -f "root@localhost: " '{ print $2}' |tail -n1` mysql -uroot -p"${defaultmysqlpwd}" --connect-expired-password <<eof alter user 'root'@'localhost' identified by 'root@2024'; eof sleep 1 mysql -uroot -p create user 'root'@'%' identified by 'root@2024'; grant all privileges on *.* to 'root'@'%'; flush privileges; 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
#!/bin/sh # copyright abandoned 1996 tcx datakonsult ab & monty program kb & detron hb # this file is public domain and comes with no warranty of any kind # mysql daemon start/stop script. # usually this is put in /etc/init.d (at least on machines sysv r4 based # systems) and linked to /etc/rc3.d/s99mysql and /etc/rc0.d/k01mysql. # when this is done the mysql server will be started when the machine is # started and shut down when the systems goes down. # comments to support chkconfig on redhat linux # chkconfig: 2345 64 36 # description: a very fast and reliable sql database engine. # comments to support lsb init script conventions ### begin init info # provides: mysql # required-start: $local_fs $network $remote_fs # should-start: ypbind nscd ldap ntpd xntpd # required-stop: $local_fs $network $remote_fs # default-start: 2 3 4 5 # default-stop: 0 1 6 # short-description: start and stop mysql # description: mysql is a very fast and reliable sql database engine. ### end init info # if you install mysql on some other places than /usr/local/mysql, then you # have to do one of the following things for this script to work: # # - run this script from within the mysql installation directory # - create a /etc/my.cnf file with the following information: # [mysqld] # basedir=<path-to-mysql-installation-directory> # - add the above to any other configuration file (for example ~/.my.ini) # and copy my_print_defaults to /usr/bin # - add the path to the mysql-installation-directory to the basedir variable # below. # # if you want to affect other mysql variables, you should make your changes # in the /etc/my.cnf, ~/.my.cnf or other mysql configuration files. # if you change base dir, you must also change datadir. these may get # overwritten by settings in the mysql configuration files. basedir=/mysql/app/mysql datadir=/mysql/data/3306/data # default value, in seconds, afterwhich the script should timeout waiting # for server start. # value here is overriden by value in my.cnf. # 0 means don't wait at all # negative numbers mean to wait indefinitely service_startup_timeout=900 # lock directory for redhat / suse. lockdir='/var/lock/subsys' lock_file_path="$lockdir/mysql" # the following variables are only set for letting mysql.server find things. # set some defaults mysqld_pid_file_path=/mysql/data/3306/mysql.pid if test -z "$basedir" then basedir=/mysql/app/mysql bindir=/mysql/app/mysql/bin if test -z "$datadir" then datadir=/mysql/data/3306/data fi sbindir=/mysql/app/mysql/bin libexecdir=/mysql/app/mysql/bin else bindir="$basedir/bin" if test -z "$datadir" then datadir="/mysql/app/3306/data" fi sbindir="$basedir/sbin" libexecdir="$basedir/libexec" fi # datadir_set is used to determine if datadir was set (and so should be # *not* set inside of the --basedir= handler.) datadir_set= # # use lsb init script functions for printing messages, if possible # lsb_functions="/lib/lsb/init-functions" if test -f $lsb_functions ; then . $lsb_functions else log_success_msg() { echo " success! $@" } log_failure_msg() { echo " error! $@" } fi path="/sbin:/usr/sbin:/bin:/mysql/app/mysql/bin:/usr/bin:$basedir/bin" export path mode=$1 # start or stop [ $# -ge 1 ] && shift other_args="$*" # uncommon, but needed when called from an rpm upgrade action # expected: "--skip-networking --skip-grant-tables" # they are not checked here, intentionally, as it is the resposibility # of the "spec" file author to give correct arguments only. case `echo "testing\c"`,`echo -n testing` in *c*,-n*) echo_n= echo_c= ;; *c*,*) echo_n=-n echo_c= ;; *) echo_n= echo_c='\c' ;; esac parse_server_arguments() { for arg do case "$arg" in --basedir=*) basedir=`echo "$arg" | sed -e 's/^[^=]*=//'` bindir="$basedir/bin" if test -z "$datadir_set"; then datadir="$basedir/data" fi sbindir="$basedir/sbin" libexecdir="$basedir/libexec" ;; --datadir=*) datadir=`echo "$arg" | sed -e 's/^[^=]*=//'` datadir_set=1 ;; --pid-file=*) mysqld_pid_file_path=`echo "$arg" | sed -e 's/^[^=]*=//'` ;; --service-startup-timeout=*) service_startup_timeout=`echo "$arg" | sed -e 's/^[^=]*=//'` ;; esac done } wait_for_pid () { verb="$1" # created | removed pid="$2" # process id of the program operating on the pid-file pid_file_path="$3" # path to the pid file. i=0 avoid_race_condition="by checking again" while test $i -ne $service_startup_timeout ; do case "$verb" in 'created') # wait for a pid-file to pop into existence. test -s "$pid_file_path" && i='' && break ;; 'removed') # wait for this pid-file to disappear test ! -s "$pid_file_path" && i='' && break ;; *) echo "wait_for_pid () usage: wait_for_pid created|removed pid pid_file_path" exit 1 ;; esac # if server isn't running, then pid-file will never be updated if test -n "$pid"; then if kill -0 "$pid" 2>/dev/null; then : # the server still runs else # the server may have exited between the last pid-file check and now. if test -n "$avoid_race_condition"; then avoid_race_condition="" continue # check again. fi # there's nothing that will affect the file. log_failure_msg "the server quit without updating pid file ($pid_file_path)." return 1 # not waiting any more. fi fi echo $echo_n ".$echo_c" i=`expr $i + 1` sleep 1 done if test -z "$i" ; then log_success_msg return 0 else log_failure_msg return 1 fi } # get arguments from the my.cnf file, # the only group, which is read from now on is [mysqld] if test -x "$bindir/my_print_defaults"; then print_defaults="$bindir/my_print_defaults" else # try to find basedir in /etc/my.cnf conf=/mysql/data/3306/my.cnf print_defaults= if test -r $conf then subpat='^[^=]*basedir[^=]*=\(.*\)$' dirs=`sed -e "/$subpat/!d" -e 's//\1/' $conf` for d in $dirs do d=`echo $d | sed -e 's/[ ]//g'` if test -x "$d/bin/my_print_defaults" then print_defaults="$d/bin/my_print_defaults" break fi done fi # hope it's in the path ... but i doubt it test -z "$print_defaults" && print_defaults="my_print_defaults" fi # # read defaults file from 'basedir'. if there is no defaults file there # check if it's in the old (depricated) place (datadir) and read it from there # extra_args="" if test -r "/mysql/data/3306/my.cnf" then extra_args="-e /mysql/data/3306/my.cnf" fi parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server` # # set pid file if not given # if test -z "$mysqld_pid_file_path" then mysqld_pid_file_path=$datadir/`hostname`.pid else case "$mysqld_pid_file_path" in /* ) ;; * ) mysqld_pid_file_path="$datadir/$mysqld_pid_file_path" ;; esac fi case "$mode" in 'start') # start daemon # safeguard (relative paths, core dumps..) cd $basedir echo $echo_n "starting mysql" if test -x $bindir/mysqld_safe then # give extra arguments to mysqld with the my.cnf file. this script # may be overwritten at next upgrade. $bindir/mysqld_safe --defaults-file=/mysql/data/3306/my.cnf --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null & wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$? # make lock for redhat / suse if test -w "$lockdir" then touch "$lock_file_path" fi exit $return_value else log_failure_msg "couldn't find mysql server ($bindir/mysqld_safe)" fi ;; 'stop') # stop daemon. we use a signal here to avoid having to know the # root password. if test -s "$mysqld_pid_file_path" then # signal mysqld_safe that it needs to stop touch "$mysqld_pid_file_path.shutdown" mysqld_pid=`cat "$mysqld_pid_file_path"` if (kill -0 $mysqld_pid 2>/dev/null) then echo $echo_n "shutting down mysql" kill $mysqld_pid # mysqld should remove the pid file when it exits, so wait for it. wait_for_pid removed "$mysqld_pid" "$mysqld_pid_file_path"; return_value=$? else log_failure_msg "mysql server process #$mysqld_pid is not running!" rm "$mysqld_pid_file_path" fi # delete lock for redhat / suse if test -f "$lock_file_path" then rm -f "$lock_file_path" fi exit $return_value else log_failure_msg "mysql server pid file could not be found!" fi ;; 'restart') # stop the service and regardless of whether it was # running or not, start it again. if $0 stop $other_args; then $0 start $other_args else log_failure_msg "failed to stop running server, so refusing to try to start." exit 1 fi ;; 'reload'|'force-reload') if test -s "$mysqld_pid_file_path" ; then read mysqld_pid < "$mysqld_pid_file_path" kill -hup $mysqld_pid && log_success_msg "reloading service mysql" touch "$mysqld_pid_file_path" else log_failure_msg "mysql pid file could not be found!" exit 1 fi ;; 'status') # first, check to see if pid file exists if test -s "$mysqld_pid_file_path" ; then read mysqld_pid < "$mysqld_pid_file_path" if kill -0 $mysqld_pid 2>/dev/null ; then log_success_msg "mysql running ($mysqld_pid)" exit 0 else log_failure_msg "mysql is not running, but pid file exists" exit 1 fi else # try to find appropriate mysqld process mysqld_pid=`pidof $libexecdir/mysqld` # test if multiple pids exist pid_count=`echo $mysqld_pid | wc -w` if test $pid_count -gt 1 ; then log_failure_msg "multiple mysql running but pid file could not be found ($mysqld_pid)" exit 5 elif test -z $mysqld_pid ; then if test -f "$lock_file_path" ; then log_failure_msg "mysql is not running, but lock file ($lock_file_path) exists" exit 2 fi log_failure_msg "mysql is not running" exit 3 else log_failure_msg "mysql is running but pid file could not be found" exit 4 fi fi ;; *) # usage basename=`basename "$0"` echo "usage: $basename {start|stop|restart|reload|force-reload|status} [ mysql server options ]" exit 1 ;; esac exit 0
cp /mysql/app/mysql/support-files/mysql.server /etc/init.d/mysqld
chmod 775 /etc/init.d/mysqld
chkconfig --list chkconfig --add mysqld chkconfig --list
service mysqld status
service mysqld stop
service mysqld start
二、数据准备,模拟生产的环境
2.1、主节点创建库及测试表
create database db01; use db01; create table dept ( deptno int unsigned auto_increment primary key comment '部门编号', dname varchar(15) comment '部门名称' , loc varchar(50) comment '部门所在位置' )engine = innodb default charset=utf8mb4 comment='员工部门表'; create table emp( empno int unsigned auto_increment primary key comment '雇员编号', ename varchar(15) comment '雇员姓名' , job varchar(10) comment '雇员职位' , mgr int unsigned comment '雇员对应的领导的编号', hiredate date comment '雇员的雇佣日期' , sal decimal(7,2) comment '雇员的基本工资' , comm decimal(7,2) comment '奖金' , deptno int unsigned comment '所在部门' , foreign key(deptno) references dept(deptno) )engine = innodb default charset =utf8mb4 comment='雇员信息表'; create table salgrade ( grade int comment '工资等级', losal int comment '此等级的最低工资', hisal int comment '此等级的最高工资' )engine=innodb default charset=utf8mb4 comment='工资等级表'; alter table salgrade add constraint pk_salgrade_primary primary key (grade,losal,hisal); create table bonus ( ename varchar(10) comment '雇员姓名', job varchar(9) comment '雇员职位', sal decimal(7,2) comment '雇员工资', comm decimal(7,2) comment '雇员奖金' )engine=innodb default charset=utf8mb4 comment='雇员奖金表' ; alter table bonus add constraint pk_bonus_primary primary key (ename,job); show full columns from emp; select * from information_schema.tables where table_schema='db01' and table_name='emp'; select * from information_schema.columns where table_schema='db01' and table_name='emp'; insert into dept values (10,'accounting','new york'); insert into dept values (20,'research','dallas'); insert into dept values (30,'sales','chicago'); insert into dept values (40,'operations','boston'); insert into emp values (7369,'smith','clerk',7902,'1980-12-17',800,null,20); insert into emp values (7499,'allen','salesman',7698,'1981-2-20',1600,300,30); insert into emp values (7521,'ward','salesman',7698,'1981-2-22',1250,500,30); insert into emp values (7566,'jones','manager',7839,'1981-4-2',2975,null,20); insert into emp values (7654,'martin','salesman',7698,'1981-9-28',1250,1400,30); insert into emp values (7698,'blake','manager',7839,'1981-5-1',2850,null,30); insert into emp values (7782,'clark','manager',7839,'1981-6-9',2450,null,10); insert into emp values (7788,'scott','analyst',7566,'87-7-13',3000,null,20); insert into emp values (7839,'king','president',null,'1981-11-17',5000,null,10); insert into emp values (7844,'turner','salesman',7698,'1981-9-8',1500,0,30); insert into emp values (7876,'adams','clerk',7788,'87-7-13',1100,null,20); insert into emp values (7900,'james','clerk',7698,'1981-12-3',950,null,30); insert into emp values (7902,'ford','analyst',7566,'1981-12-3',3000,null,20); insert into emp values (7934,'miller','clerk',7782,'1982-1-23',1300,null,10); insert into salgrade values (1,700,1200); insert into salgrade values (2,1201,1400); insert into salgrade values (3,1401,2000); insert into salgrade values (4,2001,3000); insert into salgrade values (5,3001,9999); commit;
三、搭建主从及测试
3.1、设置复制源配置
show variables like '%server_id%';
3.2、为复制创建用户
注意:主从节点都执行,方便后期主从切换
create user 'repl'@'%' identified by 'root@3306'; grant replication slave on *.* to 'repl'@'%';
测试从库连接主库
mysql -u repl -p -h 192.168.80.50
3.3、获取复制源的二进制日志位置
在主节点的不同会话中,使用 show binary log status语句确定当前二进制日志文件名和位置:
show binary log status;
(root@localhost:mysql.sock)[(none)]>show binary log status; +---------------+----------+--------------+------------------+-------------------+ | file | position | binlog_do_db | binlog_ignore_db | executed_gtid_set | +---------------+----------+--------------+------------------+-------------------+ | binlog.000001 | 11518 | | | | +---------------+----------+--------------+------------------+-------------------+ 1 row in set (0.00 sec)
3.4、主节点备份及上传到备节点
使用mysqldump工具创建要复制的所有数据库的转储。这是推荐的方法,尤其是在使用 innodb.
mysqldump --all-databases --master-data > dbdump.db
如果不使用 --master-data,则需要手动锁定单独会话中的所有表 --ignore-table使用选项 排除数据库中的所有表 --databases选项仅命名要转储的那些数据库
cd /mysql/backup/backup-db mysqldump -uroot -p --all-databases --master-data=1 > dbfulldump.db
du -sh dbfulldump.db
从节点检查目录是的否存在
mkdir -p /mysql/backup/backup-db
拷贝主节点的备份到从节点
scp -r /mysql/backup/backup-db/dbfulldump.db root@192.168.80.51:/mysql/backup/backup-db
3.5、设置副本
3.5.1、调整server_id
show variables like '%server%'; +---------------------------------+--------------------------------------+ | variable_name | value | +---------------------------------+--------------------------------------+ | character_set_server | utf8mb4 | | collation_server | utf8mb4_0900_ai_ci | | immediate_server_version | 999999 | | innodb_dedicated_server | off | | innodb_ft_server_stopword_table | | | original_server_version | 999999 | | server_id | 513306 | | server_id_bits | 32 | | server_uuid | 81c80be9-10d4-11ef-b4df-000c290e14ee | +---------------------------------+--------------------------------------+ 9 rows in set (0.00 sec)
3.5.2、导入数据
show databases; +--------------------+ | database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | +--------------------+ 4 rows in set (0.00 sec)
source dbdump.db
3.5.3、配置连接到主服务器的相关信息
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、启动从服务器的复制线程
start replica;
3.6、验证
show replica status \g show processlist \g select * from db01.emp; select * from db01.dept;
3.7、在线启用 gtid 事务
3.7.1、主库
set @@global.enforce_gtid_consistency = warn; set @@global.enforce_gtid_consistency = on; set @@global.gtid_mode = off_permissive; set @@global.gtid_mode = on_permissive; show status like 'ongoing_anonymous_transaction_count'; set @@global.gtid_mode = on;
3.7.2、从库
set @@global.enforce_gtid_consistency = warn; set @@global.enforce_gtid_consistency = on; set @@global.gtid_mode = off_permissive; set @@global.gtid_mode = on_permissive; show status like 'ongoing_anonymous_transaction_count'; set @@global.gtid_mode = on; stop replica; change replication source to source_auto_position = 1 ; start replica;
3.7.3、修改配置文件
gtid_mode = on enforce_gtid_consistency = on
3.7.4、主节点模拟增量数据产生及数据同步
create table t_city_list( id bigint auto_increment, country varchar(64), city varchar(64), constraint pk_t_city_list_id primary key(id) ); insert into t_city_list(country,city) values ('中国','北京'); insert into t_city_list(country,city) values ('中国','广州'); insert into t_city_list(country,city) values ('中国','深圳'); insert into t_city_list(country,city) values ('中国','香港'); insert into t_city_list(country,city) values ('中国','上海'); insert into t_city_list(country,city) values ('日本','东京'); insert into t_city_list(country,city) values ('日本','大阪'); commit; select * from db01.t_city_list
从节点检查
select * from t_city_list;
主节点再次新增数据
insert into t_city_list(country,city) values ('中国','中山'); insert into t_city_list(country,city) values ('中国','珠海');
从节点再次检查数据同步情况
select * from t_city_list;
3.8、主备切换
3.8.1、设置主库只读
set global read_only=on; set global super_read_only=on;
3.8.2、查看从库进程状态
show replica status \g;
确认参数项
slave_io_running 参数值为yes
slave_sql_running 参数值为yes
seconds_behind_master 参数值为 0
3.8.3、主备节点两边的executed_gtid集合对比
select @@global.gtid_executed; +-------------------------------------------+ | @@global.gtid_executed | +-------------------------------------------+ | e9adc552-10d5-11ef-81ba-000c2940f616:1-10 | +-------------------------------------------+ 1 row in set (0.00 sec) show global variables like 'gtid_%'; +----------------------------------+-------------------------------------------+ | variable_name | value | +----------------------------------+-------------------------------------------+ | gtid_executed | e9adc552-10d5-11ef-81ba-000c2940f616:1-10 | | gtid_executed_compression_period | 0 | | gtid_mode | on | | gtid_owned | | | gtid_purged | | +----------------------------------+-------------------------------------------+ 5 rows in set (0.00 sec)
3.8.4、从库停掉复制进程并清空主从信息(原从库)
stop replica; reset replica all;
3.8.5、从库关闭只读(原从库)
set global read_only=off; set global super_read_only=off;
3.8.6、主库设置执行原主库转为从库
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 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 start replica;
3.8.7、检查验证
新从节点原主节点80.50
show replica status \g;
新主节点原从节点80.51
insert into db01.t_city_list(country,city) values ('中国','兰州');
新主从节点检查数据同步情况
select * from db01.t_city_list;
到此这篇关于mysql8.4一主一从环境搭建实现的文章就介绍到这了,更多相关mysql8.4一主一从搭建内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论