MySQL 8.0.12 多数据库安装说明并配置主从同步

MySQL 8.0.12 多数据库安装说明并配置主从同步

说明

场景说明,在一台已有一个MySQL 8.0.12的服务器上再安装3个数据库并配置主从同步,但是不是通过多实例的方式,按照安装多个数据库的方式,即每一个数据库与其他的互补相关。

部署环境

IP系统主或从
10.3.248.195 CentOS Linux release 7.5.1804
10.3.248.196 CentOS Linux release 7.5.1804

安装

下载 MySQL 8.0.12 二进制安装包

wget https://cdn.mysql.com/archives/mysql-8.0/mysql-8.0.12-linux-glibc2.12-x86_64.tar.xz

解压文件

tar -xJvf mysql-8.0.12-linux-glibc2.12-x86_64.tar.xz -C /opt/

赋值并创建目录和授权

cp -r /opt/mysql-8.0.12-linux-glibc2.12-x86_64 /usr/local/mysql_3307
cp -r /opt/mysql-8.0.12-linux-glibc2.12-x86_64 /usr/local/mysql_3308
cp -r /opt/mysql-8.0.12-linux-glibc2.12-x86_64 /usr/local/mysql_3309
# 本例中不需要创建mysql 用户,因为在此环境中已经存在一个MySQL 8.0.12 数据库了。
# 如果本地没有mysql 用户,则需要创建mysql 用户
groupadd mysql
useradd -g mysql mysql
# 创建数据目录
mkdir -p /data/{mysql_3307,mysql_3308,mysql_3309}
chown -R mysql.mysql /data/{mysql_3307,mysql_3308,mysql_3309}
chmod 775 /data/{mysql_3307,mysql_3308,mysql_3309}
# 创建sock和pid 目录并授权
mkdir /var/run/mysql && chown -R mysql.mysql /var/run/mysql

配置文件

# 配置文件的位置放在/etc/路径中,下面的是3307端口的配置文件,其他端口的配置是类似的.
# 只是port、socket、mysqlx_port、mysqlx_socket、datadir、server-id、
# log-error、slow-query-log-file 参数需要更换为相应的参数即可。

cat /etc/my_3307.cnf
[client]
#password   = your_password
port        = 3307
socket      = /var/run/mysql/mysql_3307.sock



[mysqld]
port        = 3307
socket      = /var/run/mysql/mysql_3307.sock
mysqlx_port       = 33070

mysqlx_socket     = /var/run/mysql/mysqlx_3307.sock
datadir = /data/mysql_3307
skip-external-locking
key_buffer_size = 1024M
max_allowed_packet = 1M
table_open_cache = 4096
sort_buffer_size = 16M
net_buffer_length = 8K
read_buffer_size = 16M
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 256M
thread_cache_size = 512
tmp_table_size = 512M
explicit_defaults_for_timestamp=true
#skip-networking
max_connections = 10000
max_connect_errors = 100
open_files_limit = 65535
log-error = error_3307.log
slow-query-log = 1
slow-query-log-file = slow_3307.log
long_query_time = 0.2
relay_log_recovery=1
log-bin=mysql-bin
binlog_format=row
binlog_row_image=full
binlog_expire_logs_seconds=2592000
early-plugin-load = ""
server-id   = 7000
auto_increment_increment=2  
auto_increment_offset=1
log_slave_updates = 1
character-set-server=utf8mb4
sql_mode=''
default_authentication_plugin=mysql_native_password
slave_skip_errors = ddl_exist_errors

#loose-innodb-trx=0
#loose-innodb-locks=0
#loose-innodb-lock-waits=0
#loose-innodb-cmp=0
#loose-innodb-cmp-per-index=0
#loose-innodb-cmp-per-index-reset=0
#loose-innodb-cmp-reset=0
#loose-innodb-cmpmem=0
#loose-innodb-cmpmem-reset=0
#loose-innodb-buffer-page=0
#loose-innodb-buffer-page-lru=0
#loose-innodb-buffer-pool-stats=0
#loose-innodb-metrics=0
#loose-innodb-ft-default-stopword=0
#loose-innodb-ft-inserted=0
#loose-innodb-ft-deleted=0
#loose-innodb-ft-being-deleted=0
#loose-innodb-ft-config=0
#loose-innodb-ft-index-cache=0
#loose-innodb-ft-index-table=0
#loose-innodb-sys-tables=0
#loose-innodb-sys-tablestats=0
#loose-innodb-sys-indexes=0
#loose-innodb-sys-columns=0
#loose-innodb-sys-fields=0
#loose-innodb-sys-foreign=0
#loose-innodb-sys-foreign-cols=0

default_storage_engine = InnoDB
innodb_data_home_dir = /data/mysql_3307
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /data/mysql_3307
innodb_buffer_pool_size = 4096M
innodb_log_file_size = 1024M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 100M
user=root
password=Ta1mysqI@20l8


[mysql]
no-auto-rehash
default-character-set=utf8mb4

[myisamchk]
key_buffer_size = 1024M
sort_buffer_size = 16M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout


# 以上的参数可以通过下面的命令查看

/usr/local/mysql_3307/bin/my_print_defaults -e /etc/my_3307.cnf mysqld

数据库初始化

下面初始化是通过官方的启动脚本(/usr/local/mysql_3307/support-files/mysql.server) 加以补充修改而成的,增加一个初始化命令

注:此脚本只适用于单实例的数据库

cat /etc/init.d/mysql_3307
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
#
# chkconfig: - 84 16
# description: MySQL 8.0.12 Process Manager
# processname: mysql_3307
#-------------------------------------------------
#   Description :
#   Author :       bamboo
#   date:         2019/8/21
#-------------------------------------------------
#   Change Activity:
#                   2019/8/21:
#-------------------------------------------------

basedir="/usr/local/mysql_3307"
bindir="${basedir}/bin"
exec_cmd="${bindir}/mysqld"
datadir="/data/mysql_3307"
conf="/etc/my_3307.cnf"
mysqld_pid_file_path="/var/run/mysql/mysql_3307.pid"
lockdir='/var/lock/subsys'
lock_file_path="$lockdir/mysql_3307"
error_log="${datadir}/error_3307.log"

init_functions="/etc/init.d/functions"

log_success_msg()
{
   echo "SUCCESS! $@"
}
log_failure_msg()
{
   echo "ERROR! $@"
}


wait_check(){
   sleep 1
   pid=$1
   for _ in `seq 5`;do
       if (kill -0 ${pid} 2>/dev/null);then
          :
       else
          log_failure_msg "$mysqld_pid_file_path is null"
           exit 1
       fi
       sleep 1
   done
   exit 0
}


if test -f ${init_functions};then
  . ${init_functions}
fi

PATH="/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin"
export PATH

get_pid(){
   if test -r ${mysqld_pid_file_path};then
       pid=`cat ${mysqld_pid_file_path}`
       if test -n ${pid};then
           echo ${pid}
       else
           echo 0
       fi
   else
       echo 0
   fi
}

start(){
   cd ${basedir}

   if test -x ${exec_cmd};then
       pid=`get_pid`
       if test ${pid} -eq 0;then
           echo -e "Starting MySQL"
           ${exec_cmd} --defaults-file=${conf} --plugin-dir=${basedir}/lib/plugin --open-files-limit=65535 --pid-file=${mysqld_pid_file_path} --user=mysql 2>/dev/null &
           sleep 2
           pid=`get_pid`
          wait_check ${pid}; return_value=$?
           if test -w "$lockdir";
           then
               touch "$lock_file_path"
           fi
           exit $return_value
       else
          log_success_msg "MySQL server already running"
       fi
   else
      log_failure_msg "Couldn't find MySQL server (${exec_cmd})"

   fi
}

stop(){
   echo "Shutting down MySQL"
   pid=`get_pid`
   if test -s "$mysqld_pid_file_path";then
       while (kill -0 ${pid} 2>/dev/null);do
           kill ${pid}
           sleep 1
       done

   else
      log_failure_msg "MySQL server process #$pid is not running!"
       rm "$mysqld_pid_file_path"
   fi

}

status(){
   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

     mysqld_pid=`pidof $bindir/mysqld`

     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

}


initial(){
   file_num=`ls ${datadir} |wc -l`
   if test ${file_num} -eq 0;then
       ${exec_cmd} --defaults-file=${conf} --basedir=${basedir}  --datadir=${datadir} --user=mysql --initialize-insecure
       if test $? -eq 0;then
           cat ${error_log}
       else
          log_failure_msg "MySQL Initialize Failure"
           exit 2
       fi
   else
      log_failure_msg "MySQL ${datadir} has another file"
   fi
}

case $1 in
   'start')
       start
      ;;
   'stop')
       stop
      ;;
   'restart')
       stop
       start
      ;;
   'status')
      status
      ;;
   'initial')
      initial
      ;;
  *)
       basename=`basename "$0"`
         echo "Usage: $basename {start|stop|restart|status|initial} [ MySQL server options ]"
         exit 1
      ;;
esac


# 可执行权限
chmod +x /etc/init.d/mysql_3307

# 初始化数据库 (如果已经初始化或者数据目录里面不为空,会报错)
/etc/init.d/mysql_3307 initial
2019-08-21T09:20:49.840347Z 0 [System] [MY-013169] [Server] /usr/local/mysql_3307/bin/mysqld (mysqld 8.0.12) initializing of server in progress as process 57024
100 200 300 400 500 600 700 800 900 1000
100 200 300 400 500 600 700 800 900 1000
2019-08-21T09:20:55.536279Z 5 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
2019-08-21T09:20:56.245932Z 0 [System] [MY-013170] [Server] /usr/local/mysql_3307/bin/mysqld (mysqld 8.0.12) initializing of server has completed

启动数据库

/etc/init.d/mysql_3307 
Usage: mysql_3307 {start|stop|restart|status|initial} [ MySQL server options ]

/etc/init.d.mysql_3307 start

登录并且修改root 密码

# 此种方式初始化的数据库,默认密码是空,需要使用sock 登录
mysql -u root -p -S /var/run/mysql/mysql_3307.sock

# 给root 添加密码
> use mysql;
> alter user 'root'@'localhost' identified with mysql_native_password by 'x3npq4uo0ae8sb7i1dhm';
> flush privileges;

# 再次登录(指定host),执行了上面的步骤之后,那么恭喜你,使用sock 也需要密码了...
mysql -h 127.0.0.1 -u root -P 3307 -p

密码的生成方式有很多,可以使用pwgen 生成你所需要的密码,还可以自己编写一个密码生成器,下面说一下这两种方式

# 使用pwgen (如果使用yum 还是不能安装,那么可能需要首先安装一个epel源)
yum install epel-release -y && yum install pwgen -y
pwgen -h
Usage: pwgen [ OPTIONS ] [ pw_length ] [ num_pw ]

Options supported by pwgen:
 -c or --capitalize
  Include at least one capital letter in the password
 -A or --no-capitalize
  Don't include capital letters in the password
 -n or --numerals
  Include at least one number in the password
 -0 or --no-numerals
  Don't include numbers in the password
 -y or --symbols
  Include at least one special symbol in the password
 -r <chars> or --remove-chars=<chars>
  Remove characters from the set of characters to generate passwords
 -s or --secure
  Generate completely random passwords
 -B or --ambiguous
  Don't include ambiguous characters in the password
 -h or --help
  Print a help message
 -H or --sha1=path/to/file[#seed]
  Use sha1 hash of given file as a (not so) random generator
 -C
  Print the generated passwords in columns
 -1
  Don't print the generated passwords in columns
 -v or --no-vowels
  Do not use any vowels so as to avoid accidental nasty words


pwgen

chieH0Oo pae8ShuB ie0QuuaV tha6aePa QuahLoo4 ifeNe9Ai aa0SeiGh Quo6theu
aht6OoH2 ief6Sohs aic5wieL iej6aiCh Jeew1eex aey5Ahju oehoP7ae Uu4woeye
oibiej6Y phae5aeT ohng0ahR Aigh8abi bai3la5E Feyib6oh riexea6M Ti0ahng7
Moo9aeGh Uo5iag9A iKeeju2u iJeiGh7l phaH5ohz Uo2nooba Na6ahQue Airie4tu
chaeNub3 aiNooch5 Cheth5oo vaevei5A ooDie0Uu fieNgoe3 Ohsu8xej EePhae8j
Ivog3euc Iph5jahV iePh1lai oal2xuB8 Hoof5pho eeb6Oe7y Doo1Dihe UeYo8xaG
eiMaeke8 ahraim1U ooThied9 xai2Aigi akea1ooL Eothei6E pheeKoh5 WiNg7ti6
soh8EiNg Ahsh7nit iF0pahye ui2Bi3ai Yid6bei1 tee0Eis8 OokouNg5 iey8fa7E
Udu3wedo faph3eYi aibai9Ta Ke3Oogha iecahz6B ZahVie9z rae7eeR4 isu3Eiyu
aiPhoh8a thizai1J Aegahj8a iexooz7G ahFa8Loo aeSo0iax ahb6Liwa Choot6ru
Naing7ae hiew9aeT lus6Chu2 yaegu6Ab daTei9ee iPh9iez1 Kahm4aav fei8Aeta
auD3Phou Gie9eyae ooth0Dee shooge8Y uJ7yailo deecon7O Ix2eathe Zahghai5
Nepo4Xoo ohN6Xoop MeiKae0e so5Riexu aiBab3ai Oshei7re ee9BahNg Ra5booT6
ooN6leve Ao4ool4e Fiequ2Ie Oo6uquu2 Ekeef5re eeM9paKu ohh0EeMe eBe9thae
gaex0AiH vi3Saeho Oongei2o auQu8cay nu4shieT Rahicu4y quah9ahD AaM0loht
EiK6siey IJ2ure3n alaFiek7 uc1Aingi Peeso5wo Foocoo3n tho1Nige PhioM9Oo
Tae8eequ PiezahT2 hieW7aeG EaDaeki3 tah3eviZ ieHiede3 cai6Xiif ohm3daiX
ohnie8Ei oriep6Sh ahCoo9oh Eerohth4 ahCh0IPh EaN2ce1d chaB0nei ua8uPair
Agae2aeT ivu3Eice aPoo9kah Thus5ooc ceiVohv2 hie9peiH soo5Feej Lah6cieg
ooVu1oov saebae3M opheeFe5 kaShep6L aoThaes9 thaiv2aH nooh4Ife Lie5eng6

# 使用自己编写的脚本(有需要可以找我)
./password_generator.py
Usage: password_generator.py [options]

Options:
 -h, --help show this help message and exit
 -m METHOD   a: 数字,大小写,特殊字符组合
            d: 数字
            l: 小写字母
            u: 大写字母
            p: 特殊字符
            dl: 数字,小写字符组合
            du: 数字,大写字符组合
            dp: 数字,特殊字符组合
            lu: 小写字符,大写字符组合
            lp: 小写字符,特殊字符组合
            up: 大写字符,特殊字符组合
            dlu:
            数字,大小写字符组合
 -n NUMBER   输入密码生成的位数,默认是20位
            示例: ./password_generator.py -m a
 -w UNIQ     是否允许重复,默认值为t<不重复>,f<重复>

配置主从同步

要注意,主服务器和从服务器,server_id 不能相同

主服务器

# 配置文件,至少要设置下面两个参数
[mysqld]
log-bin=mysql-bin
server-id = 7000

从服务器

# 配置文件,至少要设置下面参数
[mysqld]
server-id = 7001

主服务器

# 创建用于复制操作的用户
> CREATE USER 'repl'@'10.3.248.196' IDENTIFIED WITH mysql_native_password BY 'idgfkn7p';
> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.3.248.196';
> flush privileges;
# 获取主服务器当前binary log 文件名和位置(position)
> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000007 |     2695 |             |                 |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

从服务器

> CHANGE MASTER TO
MASTER_HOST='10.3.248.195',
MASTER_PORT=3307,

MASTER_USER='repl',
MASTER_PASSWORD='idgfkn7p',
MASTER_LOG_FILE='mysql-bin.000004',
MASTER_LOG_POS=2695;

> show slave status\G
> start slave;
> show slave status\G
# 如果下面的两个状态是yes 就说明是OK啦
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

END

posted @ 2021-08-26 11:10  大川哥  阅读(180)  评论(0编辑  收藏  举报