首页 技术 正文
技术 2022年11月20日
0 收藏 439 点赞 2,508 浏览 24596 个字

文章目录

MySQL 源码编译安装(CentOS-6.6+MySQL-5.6)

部署环境

操作系统:CentOS-6.6-x86_64-bin-DVD1.iso MySQL 版本:mysql-5.6.26.tar.gz 操作用户:root

系统 IP:192.168.1.205 主机名:edu-mysql-01

配置:4 核、4G 内存

一、服务器配置:

1、配置网络

# vi /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE=eth0BOOTPROTO=staticNM_CONTROLLED=noONBOOT=yesTYPE=EthernetHWADDR=00:50:56:a1:12:53IPADDR=192.168.1.205NETMASK=255.255.255.0GATEWAY=192.168.1.1DNS1=223.5.5.5DNS2=223.6.6.6

2、设置主机名

# vi /etc/sysconfig/networkNETWORKING=yesHOSTNAME=edu-mysql-01

3、设置 IP 与主机名的映射

# vi /etc/hosts127.0.0.1 edu-mysql-01192.168.1.205 edu-mysql-01

4、两台数据库服务器的的 selinux 都要 disable

(永久关闭 selinux,请修改/etc/selinux/config,将 SELINUX 改为 disabled)

# vi /etc/selinux/configSELINUX=disabled

5、重启操作系统

# reboot

二、源码安装 MySQL5.6.26:

1、使用下面的命令检查是否安装有 MySQL Server: # rpm -qa | grep mysql mysql-libs-5.1.73-3.el6_5.x86_64

如果是 CentOS7 以上,请使用以下命令查看:

# rpm -qa | grep mariadbmariadb-libs-5.5.41-2.el7_0.x86_64

(因为没有 MySQL 服务,因此没必要卸载。mysql-libs 是 MySQL 的必要包)

(如果有的话可通过下面的命令来卸载掉,rpm -e mysql //普通删除模式 )

2、改防火墙设置,打开 3306 端口:

# vi /etc/sysconfig/iptables

增加如下行:

## MySQL-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT

重启防火墙:

# service iptables restart

3、新增 mysql 用户组:

# groupadd mysql

4、新增 mysql 用户,并添加到 mysql 用户组:

# useradd -r -g mysql mysql

5、新建 MySQL 执行文件目录(后面会把编译好的 mysql 程序安装到这个目录):

# mkdir -p /usr/local/mysql

(-p 参数的作用是:如果最终目录的父目录不存在也会一并创建)

6、新建 MySQL 数据库数据文件目录:

# mkdir -p /home/mysql/data# mkdir -p /home/mysql/logs# mkdir -p /home/mysql/temp

(注意:上面的 logs 及 temp 目录是为了以后将 MySQL 的数据文件与执行程序文件分离, 如果你打算设置到不同的路径,注意修改对应的执行命令和数据库初始化脚本。 正式生产环 境,建议数据目录和日志目录都使用单独的分区来挂载,不 同分区属 于不同的磁 盘 或 磁 盘 组。)

7、增加 PATH 环境变量搜索路径:

# vi /etc/profile##在 profile 文件末尾增加两行# mysql env paramPATH=/usr/local/mysql/bin:/usr/local/mysql/lib:$PATHexport PATH

使 PATH 搜索路径立即生效:

# source /etc/profile

8、安装编译 MySQL 需要的依赖包:

(mysql 从 5.5 版本开始,不再使用./configure 编译,而是使用 cmake 编译器,具体的 cmake 编译参数可以参考 mysql 官网文档 http://dev.mysql.com/doc/refman/5.5/en/source-configuration-options.html,安装基 本依赖包,先用 yum 安装 cmake、automake 、autoconf ,另 MySQL 5.5.x 需要最少安装的 包有:bison,gcc、gcc-c++、ncurses-devel):

# yum install make cmake gcc gcc-c++ bison bison-devel ncurses ncurses-devel autoconf automake

9、进入/usr/local/src 目录,上传 mysql-5.6.26.tar.gz 源代码到/usr/local/src 目录:

# cd /usr/local/src

10、开始编译安装 mysql-5.6.26: 解压缩源码包:

# tar -zxvf mysql-5.6.26.tar.gz

进入解压缩源码目录:

# cd mysql-5.6.26

使用 cmake 源码安装 mysql(如果你打算安装到不同的路径,注意修改下面语句中 /usr/local/mysql 和/home/mysql/data 路径!)

[root@edu-mysql-01 mysql-5.6.26]# cmake \-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \-DMYSQL_UNIX_ADDR=/usr/local/mysql/mysql.sock \-DDEFAULT_CHARSET=utf8 \-DDEFAULT_COLLATION=utf8_general_ci \-DWITH_MYISAM_STORAGE_ENGINE=1 \-DWITH_INNOBASE_STORAGE_ENGINE=1 \-DWITH_ARCHIVE_STORAGE_ENGINE=1 \-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \-DWITH_MEMORY_STORAGE_ENGINE=1 \-DWITH_READLINE=1 \-DENABLED_LOCAL_INFILE=1 \-DMYSQL_DATADIR=/home/mysql/data \-DMYSQL_USER=mysql \-DMYSQL_TCP_PORT=3306 \-DENABLE_DOWNLOADS=1

上面的这些复制完,回车,然后就开始 cmake 的过程,一般时间不会很长。

配置解释:

-DCMAKE_INSTALL_PREFIX=/usr/local/mysql 设置安装目录 -DMYSQL_DATADIR=/home/mysql/data 设置数据库存放目录 -DMYSQL_UNIX_ADDR=/usr/local/mysql/mysql.sock 设置 UNIX socket 目录 -DMYSQL_USER=mysql 设置运行用户-DDEFAULT_CHARSET=utf8 设置默认字符集,默认 latin1 -DEFAULT_COLLATION=utf8_general_ci 设置默认校对规则,默认 latin1_general_ci -DWITH_INNOBASE_STORAGE_ENGINE=1 添加 InnoDB 引擎支持 -DENABLE_DOWNLOADS=1 自动下载可选文件,比如自动下载谷歌的测试包 -DMYSQL_TCP_PORT=3306 设置服务器监听端口,默认 3306-DSYSCONFDIR=/etc 设置 my.cnf 所在目录,默认为安装目录)

执行过程中会出现:

CMake Error: Problem with tar_extract_all(): Invalid argumentCMake Error: Problem extracting tar: /usr/local/src/mysql-5.6.26/source_downloads/gmoc k- 1.6.0.zip

解决方法:

cd mysql 目录下面会发现有一个 source_downloads 目录,需要解压 unzip gmock-1.6.0.zip,然 后再重新执行上述配置过程。当然你也可以去掉-DENABLE_DOWNLOADS=1 这个选项,不编 译谷歌的测试包也没有什么问题,但是之前的某些版本会出现无法编译的问题.

11、cmake 结束后开始编译源码,这一步时间会较长,请耐心等待:

# make

12、安装编译好的程序:

# make install

(注意:如果需要重装 mysql,在/usr/local/src/mysql-5.6.26 在执行下 make install 就可以了, 不需要再 cmake 和 make)

13、清除安装临时文件:

# make clean

14、修改 mysql 目录拥有者为 mysql 用户:

 # chown -Rf mysql:mysql /usr/local/mysql # chown -Rf mysql:mysql /home/mysql

15、进入 mysql 执行程序的安装路径:

# cd /usr/local/mysql

16、执行初始化配置脚本,创建系统自带的数据库和表(注意:路径/home/mysql/data 需要 换成你自定定义的数据库存放路径):

# scripts/mysql_install_db --user=mysql --basedir=/usr/local/mysql --datadir=/home/mysql/data Installing MySQL system tables...2015-12-13 15:21:53 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (seedocumentation for more details).2015-12-13 15:21:53 0 [Note] /usr/local/mysql/bin/mysqld (mysqld 5.6.26) starting as process 17362 ...2015-12-13 15:21:53 17362 [Note] InnoDB: Using atomics to ref count buffer pool pages 2015-12-13 15:21:53 17362 [Note] InnoDB: The InnoDB memory heap is disabled2015-12-13 15:21:53 17362 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins 2015-12-13 15:21:53 17362 [Note] InnoDB: Memory barrier is not used2015-12-13 15:21:53 17362 [Note] InnoDB: Compressed tables use zlib 1.2.32015-12-13 15:21:53 17362 [Note] InnoDB: Using CPU crc32 instructions2015-12-13 15:21:53 17362 [Note] InnoDB: Initializing buffer pool, size = 128.0M2015-12-13 15:21:53 17362 [Note] InnoDB: Completed initialization of buffer pool2015-12-13 15:21:53 17362 [Note] InnoDB: The first specified data file ./ibdata1 did not exist: a new database to be created!2015-12-13 15:21:53 17362 [Note] InnoDB: Setting file ./ibdata1 size to 12 MB2015-12-13 15:21:53 17362 [Note] InnoDB: Database physically writes the file full: wait... 2015-12-13 15:21:53 17362 [Note] InnoDB: Setting log file ./ib_logfile101 size to 48 MB 2015-12-13 15:21:53 17362 [Note] InnoDB: Setting log file ./ib_logfile1 size to 48 MB2015-12-13 15:21:53 17362 [Note] InnoDB: Renaming log file ./ib_logfile101 to ./ib_logfile0 2015-12-13 15:21:53 17362 [Warning] InnoDB: New log files created, LSN=457812015-12-13 15:21:53 17362 [Note] InnoDB: Doublewrite buffer not found: creating new 2015-12-13 15:21:53 17362 [Note] InnoDB: Doublewrite buffer created2015-12-13 15:21:53 17362 [Note] InnoDB: 128 rollback segment(s) are active.2015-12-13 15:21:53 17362 [Warning] InnoDB: Creating foreign key constraint system tables. 2015-12-13 15:21:53 17362 [Note] InnoDB: Foreign key constraint system tables created 2015-12-13 15:21:53 17362 [Note] InnoDB: Creating tablespace and datafile system tables. 2015-12-13 15:21:53 17362 [Note] InnoDB: Tablespace and datafile system tables created. 2015-12-13 15:21:53 17362 [Note] InnoDB: Waiting for purge to start2015-12-13 15:21:53 17362 [Note] InnoDB: 5.6.26 started; log sequence number 02015-12-13 15:21:53 17362 [Note] Binlog end2015-12-13 15:21:53 17362 [Note] InnoDB: FTS optimize thread exiting.2015-12-13 15:21:53 17362 [Note] InnoDB: Starting shutdown...2015-12-13 15:21:54 17362 [Note] InnoDB: Shutdown completed; log sequence number 1625977 OKFilling help tables...2015-12-13 15:21:54 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).2015-12-13 15:21:54 0 [Note] /usr/local/mysql/bin/mysqld (mysqld 5.6.26) starting as process 17384 ...2015-12-13 15:21:54 17384 [Note] InnoDB: Using atomics to ref count buffer pool pages 2015-12-13 15:21:54 17384 [Note] InnoDB: The InnoDB memory heap is disabled 2015-12-13 15:21:54 17384 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins 2015-12-13 15:21:54 17384 [Note] InnoDB: Memory barrier is not used2015-12-13 15:21:54 17384 [Note] InnoDB: Compressed tables use zlib 1.2.32015-12-13 15:21:54 17384 [Note] InnoDB: Using CPU crc32 instructions2015-12-13 15:21:54 17384 [Note] InnoDB: Initializing buffer pool, size = 128.0M2015-12-13 15:21:54 17384 [Note] InnoDB: Completed initialization of buffer pool2015-12-13 15:21:54 17384 [Note] InnoDB: Highest supported file format is Barracuda. 2015-12-13 15:21:54 17384 [Note] InnoDB: 128 rollback segment(s) are active.2015-12-13 15:21:54 17384 [Note] InnoDB: Waiting for purge to start2015-12-13 15:21:54 17384 [Note] InnoDB: 5.6.26 started; log sequence number 1625977 2015-12-13 15:21:55 17384 [Note] Binlog end2015-12-13 15:21:55 17384 [Note] InnoDB: FTS optimize thread exiting.2015-12-13 15:21:55 17384 [Note] InnoDB: Starting shutdown...2015-12-13 15:21:56 17384 [Note] InnoDB: Shutdown completed; log sequence number 1625987 OKTo start mysqld at boot time you have to copy support-files/mysql.server to the right place for your systemPLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER ! To do so, start the server, then issue the following commands:/usr/local/mysql/bin/mysqladmin -u root password 'new-password' /usr/local/mysql/bin/mysqladmin -u root -h edu-mysql-02 password 'new-password'Alternatively you can run: /usr/local/mysql/bin/mysql_ secure_installationwhich will also give you the option of removing the test databases and anonymous user created by default. This is strongly recommended for production servers.See the manual for more instructions. You can start the MySQL daemon with:cd . ; /usr/local/mysql/bin/mysqld_safe &You can test the MySQL daemon with mysql-test-run.plcd mysql-test ; perl mysql-test-run.plPlease report any problems at http://bugs.mysql.com/The latest information about MySQL is available on the web athttp://www.mysql.comSupport MySQL by buying support/licenses at http://shop.mysql.comNew default config file was created as /usr/local/mysql/my.cnf and will be used by default by the server when you start it.You may edit this file to change server settingsWARNING: Default config file /etc/my.cnf exists on the system This file will be read by default by the MySQL serverIf you do not want to use this, either remove it, or use the --defaults-file argument to mysqld_safe when starting the server

17、初始化脚本在/usr/local/mysql/下生成了配置文件 my.cnf,需要更改该配置文件的所有者:

# ls -lah

[root@edu-mysql-01 mysql] # chown -Rf mysql:mysql /usr/local/mysql/my.cnf

18、注意:

(1)Tips:在启动 MySQL 服务时,会按照一定次序搜索 my.cnf,先在/etc 目录下找,找不 到则会搜索 mysql 程序目录下是否有 my.cnf

(2)需要注意 CentOS 6 版操作系统的最小安装完成后,即使没有安装 mysql,在/etc 目录 下也会存在一个 my.cnf 文件,建议将此文件更名为其他的名字,否则该文件会干扰源码安 装的 MySQL 的正确配置,造成无法启动。修改/etc/my.cnf 操作如下:

可以:mv /etc/my.cnf /etc/my.cnf.bak

也可以:删除掉/etc/my.cnf 这个文件:rm /etc/my.cnf

如果你需要用于生产环境,不要急着做下面的 mysql 启动操作。建议把上一步骤中 mysql 初

始化生成的/usr/local/mysql/my.cnf 删除,然后把你优化好的 mysql 配置文件 my.cnf 放到/etc 下。(这是做 mysql 主从复制和 mysql 优化的经验!)

(我们这里使用/etc/my.cnf)

19、编辑/etc/my.cnf: # vi my.cnf

[client]port = 3306socket = /usr/local/mysql/mysql.sock[mysqld]character-set-server = utf8 collation-server = utf8_general_ciskip-external-locking skip-name-resolveuser = mysqlport = 3306basedir = /usr/local/mysqldatadir = /home/mysql/datatmpdir = /home/mysql/temp# server_id = .....socket = /usr/local/mysql/mysql.sock log-error = /home/mysql/logs/mysql_error.log pid-file = /home/mysql/mysql.pidopen_files_limit = 10240back_log = 600 max_connections=500 max_connect_errors = 6000 wait_timeout=605800#open_tables = 600 #table_cache = 650 #opened_tables = 630max_allowed_packet = 32Msort_buffer_size = 4M join_buffer_size = 4M thread_cache_size = 300query_cache_type = 1 query_cache_size = 256M query_cache_limit = 2M query_cache_min_res_unit = 16ktmp_table_size = 256M max_heap_table_size = 256Mkey_buffer_size = 256M read_buffer_size = 1M read_rnd_buffer_size = 16M bulk_insert_buffer_size = 64Mlower_case_table_names=1default-storage-engine = INNODB//这里注意包括mongodb中也是,设置为物理内存的一般到2/3innodb_buffer_pool_size =2Ginnodb_log_buffer_size = 32M innodb_log_file_size = 128M innodb_flush_method =O_DIRECT#####################thread_concurrency = 32//超过两秒的话,就把日志输入到下面的slow log,用来辅助做性能调优long_query_time= 2slow-query-log = onslow-query-log-file =/home/mysql/logs/mysql-slow.log  [mysqldump]quickmax_allowed_packet = 32M[mysqld_safe] log-error=/var/log/mysqld.log pid-file=/va r/run/mysqld/m ysq ld. pid

20、复制服务启动脚本:

# cp /usr/local/mysql/support-files/mysql.server/etc/init.d/mysql

21、启动 MySQL 服务:

# service mysql startStarting MySQL.. SUCCESS!

(初次启动会在/usr/local/mysql 目录下生成 mysql.sock 文件)

22、设置 MySQL 开机自动启动服务:

# chkconfig mysql on

设置 MySQL 数据库 root 用户的本地登录密码(初始用户没有密码):

# mysqladmin -u root password 'roncoo'

23、登录并修改 MySQL 用户 root 的密码:

# mysql -uroot -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2Server version: 5.6.26-log Source distributionCopyright (c) 2000, 2015, 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>mysql> show databases; +------------------- -+| Database | +------------------- -+| information_schema || mysql | | performance_schema | | test | +------------------- -+4 rows in set (0.00 sec)mysql> use mysql;Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

修改 root 用户密码:

mysql> update user set Password = password('roncoo.com') where User='root'; Query OK, 4 rows affected (0.00 sec)Rows matched: 5 Changed: 4 Warnings: 0mysql> flush privileges;Query OK, 0 rows affected (0.00 sec)

允许 root 远程登录,设置远程登录密码:www.roncoo.com

mysql> use mysql;mysql>GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'www.roncoo.com' WITH GRANT OPTION;mysql> flush privileges;mysql> exit;

注意:真实生产环境,应用操作不要使用 root 用户。

重新登录

[root@edu-mysql-01 ~]# mysql -uroot -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 9Server version: 5.6.26-log Source distributionCopyright (c) 2000, 2015, 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>

24、运行安全设置脚本, 强烈建议生产服务器使用(可选):

 [root@edu-mysql-01 ~]# /usr/local/mysql/bin/mysql_secure_installationNOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!In order to log into MySQL to secure it, we'll need the current password for the root user. If you've just installed MySQL, and you haven't set the root password yet, the password will be blank, so you should just press enter here.Enter current password for root (enter for none): ----->此处输入 root 密码 OK, successfully used password, moving on...Setting the root password ensures that nobody can log into the MySQL root user without the proper authorisation.You already have a root password set, so you can safely answer 'n'.Change the root password? [Y/n] n -----> 上已为 root 设置了密码,此处可输 n ... skipping.By default, a MySQL installation has an anonymous user, allowing anyone to loginto MySQL without having to have a user account created for them. This isintended only for testing, and to make the installationgo a bit smoother. You should remove them before moving into a productionenvironment.Remove anonymous users? [Y/n] Y ------> 删除匿名用户 ... Success!Normally, root should only be allowed to connect from 'localhost'. This ensures that someone cannot guess at the root password from the network.Disallow root login remotely? [Y/n] n -----> 一般不允许 root 远程登录,可添加普通用户, 然后设置允许远程登录... skipping.By default, MySQL comes with a database named 'test' that anyone can access.This is also intended only for testing, and should be removed before moving intoa production environment.  Remove test database and access to it? [Y/n] Y - Dropping test database...... Success!- Removing privileges on test database...... Success!-----> 删除 test 库及相应权限Reloading the privilege tables will ensure that all changes made so far will take effect immediately.Reload privilege tables now? [Y/n] Y -----> 重新加载权限表使设置生效... Success!All done! If you've completed all of the above steps, your MySQLinstallation should now be secure.Thanks for using MySQL!Cleaning up...

25、重启服务器,检测 mysql 是否能开机自动启动: [root@edu-mysql-01 ~] # reboot

MySQL主从复制的配置

环境

操作系统:CentOS-6.6-x86_64-bin-DVD1.iso

MySQL 版本:mysql-5.6.26.tar.gz

主节点 IP:192.168.1.205 主机名:edu-mysql-01

从节点 IP:192.168.1.206 主机名:edu-mysql-02

主机配置:4 核 CPU、4G 内存

依赖课程

《高可用架构篇–第 13 节–MySQL 源码编译安装(CentOS-6.6+MySQL-5.6)》

MySQL 主从复制官方文档

http://dev.mysql.com/doc/refman/5.6/en/replication.html

MySQL 主从复制的方式

MySQL5.6 开始主从复制有两种方式:基于日志(binlog)、基于 GTID(全局事务标示符)。 本教程主要讲基于日志(binlog)的复制。

MySQL 主从复制(也称 A/B 复制)的原理

(1) Master将数据改变记录到二进制日志(binary log)中,也就是配置文件log-bin指定的文件, 这些记录叫做二进制日志事件(binary log events);

(2) Slave 通过 I/O 线程读取 Master 中的 binary log events 并写入到它的中继日志(relay log); (3) Slave 重做中继日志中的事件,把中继日志中的事件信息一条一条的在本地执行一次,完 成数据在本地的存储,从而实现将改变反映到它自己的数据(数据重放)。

主数据库的每次变更(增删改查)都会记录到二进制文件总

从数据库有两个线程,一个是io线程去读取二进制文件,并写入到自己的中继日志中,还有一个sql线程,数据重放到自己的数据库中。

主从配置需要注意的点

(1)主从服务器操作系统版本和位数一致;

(2) Master 和 Slave 数据库的版本要一致;

(3) Master 和 Slave 数据库中的数据要一致;

(4) Master 开启二进制日志,Master 和 Slave 的 server_id 在局域网内必须唯一;

主从配置的简要步骤

1、Master 上的配置

(1) 安装数据库;

(2) 修改数据库配置文件,指明 server_id,开启二进制日志(log-bin);

(3) 启动数据库,查看当前是哪个日志,position 号是多少;

(4) 登录数据库,授权数据复制用户(IP 地址为从机 IP 地址,如果是双向主从,这里的 还需要授权本机的 IP 地址,此时自己的 IP 地址就是从 IP 地址);

(5) 备份数据库(记得加锁和解锁);

(6) 传送备份数据到 Slave 上;

(7) 启动数据库;

以下步骤,为单向主从搭建成功,想搭建双向主从需要的步骤:

(1) 登录数据库,指定 Master 的地址、用户、密码等信息(此步仅双向主从时需要);

(2) 开启同步,查看状态;

2、Slave 上的配置

(1) 安装数据库;

(2) 修改数据库配置文件,指明 server_id(如果是搭建双向主从的话,也要开启二进制 日志 log-bin);

(3) 启动数据库,还原备份;

(4) 查看当前是哪个日志,position 号是多少(单向主从此步不需要,双向主从需要);

(5) 指定 Master 的地址、用户、密码等信息;

(6) 开启同步,查看状态。

单向主从环境(也称 MySQL A/B 复制)的搭建

1、Master(192.168.1.205)和 Slave(192.168.1.206)上都安装了相同版本的数据库(mysql- 5.6.26.tar.gz),参考《高可用架构篇–第 13 节–MySQL 源码编译安装(CentOS6.6+MySQL5.6)》。

注意:两台数据库服务器的的 selinux 都要 disable(永久关闭 selinux,请修改/etc/selinux/config, 将 SELINUX 改为 disabled)

2、修改 Master 的配置文件/etc/my.cnf

[root@edu-mysql-01 ~]# vi /etc/my.cnf ## 在 [mysqld] 中增加以下配置项## 设置 server_id,一般设置为 IP server_id=205## 复制过滤:需要备份的数据库,输出 binlog#binlog-do-db=roncoo## 复制过滤:不需要备份的数据库,不输出(mysql 库一般不同步)binlog-ignore-db=mysql## 开启二进制日志功能,可以随便取,最好有含义log-bin=edu-mysql-bin## 为每个 session 分配的内存,在事务过程中用来存储二进制日志的缓存 binlog_cache_size=1M## 主从复制的格式(mixed,statement,row,默认格式是 statement)binlog_format=mixed## 二进制日志自动删除/过期的天数。默认值为 0,表示不自动删除。expire_logs_days=7## 跳过主从复制中遇到的所有错误或指定类型的错误,避免 slave 端复制中断。 ## 如:1062 错误是指一些主键重复,1032 错误是因为主从数据库数据不一致slave_skip_errors=1062

(如想了解以上参数的更多详细解析,大家可以直接百度参数名)

2.1 复制过滤可以让你只复制服务器中的一部分数据,有两种复制过滤: (1) 在 Master 上过滤二进制日志中的事件;

(2) 在 Slave 上过滤中继日志中的事件。如下:

2.2 MySQL 对于二进制日志 (binlog)的复制类型

(1) 基于语句的复制:在 Master 上执行的 SQL 语句,在 Slave 上执行同样的语句。MySQL 默 认采用基于语句的复制,效率比较高。一旦发现没法精确复制时,会自动选着基于行的复制。 (2) 基于行的复制:把改变的内容复制到 Slave,而不是把命令在 Slave 上执行一遍。从 MySQL5.0 开始支持。

(3) 混合类型的复制:默认采用基于语句的复制,一旦发现基于语句的无法精确的复制时, 就会采用基于行的复制。

3、启动/重启 Master 数据库服务,登录数据库,创建数据同步用户,并授予相应的权限

[root@edu-mysql-01 ~]# service mysql restartShutting down MySQL..[ OK ]Starting MySQL..[ OK ][root@edu-mysql-01 ~]# mysql -uroot -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1Server version: 5.6.26-log Source distributionCopyright (c) 2000, 2015, 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.##创建数据同步用户,并授予相应的权限,允许从节点是192.168.1.206,并且密码已经帮它设置好了是roncoo.123mysql> grant replication slave, replication client on *.* to 'repl'@'192.168.1.206' identified by 'roncoo.123';Query OK, 0 rows affected (0.00 sec)## 刷新授权表信息mysql> flush privileges;Query OK, 0 rows affected (0.00 sec)## 查看 position 号,记下 position 号(从机上需要用到这个 position 号和现在的日志文件) mysql> show master status;

4、创建 roncoo 库、表,并写入一定量的数据,用于模拟现有的业务系统数据库 create

database if not exists roncoo default charset utf8 collate utf8_general_ci;use roncoo;DROP TABLE IF EXISTS `edu_user`;CREATE TABLE `edu_user` (`Id` int(11) NOT NULL AUTO_INCREMENT,`userName` varchar(255) NOT NULL DEFAULT '' COMMENT '用户名', `pwd` varchar(255) NOT NULL DEFAULT '' COMMENT '密码', PRIMARY KEY (`Id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='用户信息表'; INSERTINTO `edu_user` VALUES (1,'吴水成','123456'),(2,'清风','123456'),(3,'龙果','roncoo.com');

5、为保证 Master 和 Slave 的数据一致,我们采用主备份,从还原来实现初始数据一致

## 先临时锁表mysql> flush tables with read lock;Query OK, 0 rows affected (0.00 sec)//注意这步是退出mysql执行的## 这里我们实行全库备份,在实际中,我们可能只同步某一个库,那也可以只备份一个库[root@edu-mysql-01 ~]# mysqldump -p3306 -uroot -p --add-drop-table roncoo > /tmp/edu-master-roncoo.sql;Warning: Using a password on the command line interface can be insecure. Enter password:[root@edu-mysql-01 ~]# cd /tmp[root@edu-mysql-01 tmp]# lltotal 644-rw-r--r-- 1 root root 644266 Dec 20 04:10 edu-master-roncoo.sql## 注意:实际生产环境中大数据量(超 2G 数据)的备份,建议不要使用 mysqldump 进行 比分,因为会非常慢。此时推荐使用 XtraBackup 进行备份。## 解锁表mysql> unlock tables;Query OK, 0 rows affected (0.00 sec)

将 Master 上备份的数据远程传送到 Slave 上,以用于 Slave 配置时恢复数据

[root@edu-mysql-01 ~]# scp /tmp/edu-master-roncoo.sql root@192.168.1.206:/tmp/ root@192.168.1.206's password:edu-master-roncoo.sql 100% 629KB 629.2KB/s 00:00[root@edu-mysql-01 ~]#

6、接下来处理 Slave(192.168.1.206),配置文件只需修改一项,其余配置用命令来操作

[root@edu-mysql-02 ~]# vi /etc/my.cnf## 在 [mysqld] 中增加以下配置项## 设置 server_id,一般设置为 IPserver_id=206//有时候从节点也可能成为别人的主节点## 复制过滤:需要备份的数据库,输出 binlog#binlog-do-db=roncoo##复制过滤:不需要备份的数据库,不输出(mysql 库一般不同步)binlog-ignore-db=mysql## 开启二进制日志,以备 Slave 作为其它 Slave 的 Master 时使用log-bin=edu-mysql-slave1-bin## 为每个 session 分配的内存,在事务过程中用来存储二进制日志的缓存binlog_cache_size = 1M## 主从复制的格式(mixed,statement,row,默认格式是 statement)binlog_format=mixed## 二进制日志自动删除/过期的天数。默认值为 0,表示不自动删除。expire_logs_days=7## 跳过主从复制中遇到的所有错误或指定类型的错误,避免 slave 端复制中断。## 如:1062 错误是指一些主键重复,1032 错误是因为主从数据库数据不一致slave_skip_errors=1062## relay_log 配置中继日志relay_log=edu-mysql-relay-bin## log_slave_updates 表示 slave 将复制事件写进自己的二进制日志//看下图,因为可能从节点再作为主节点log_slave_updates=1## 防止改变数据(除了特殊的线程)read_only=1

如果 Slave 为其它 Slave 的 Master 时,必须设置 bin_log。在这里,我们开启了二进制日志, 而且显式的命名(默认名称为 hostname,但是,如果 hostname 改变则会出现问题)。 relay_log 配置中继日志,log_slave_updates 表示 slave 将复制事件写进自己的二进制日志。 当设置 log_slave_updates 时,你可以让 slave 扮演其它 slave 的 master。此时,slave 把 SQL 线程执行的事件写进行自己的二进制日志(binary log),然后,它的 slave 可以获取这些事件 并执行它。如下图所示(发送复制事件到其它 Slave):

也有这种需求:需要三个,最后一个只做数据备份

7、保存后重启 MySQL 服务,还原备份数据

[root@edu-mysql-02 ~]# service mysql restartShutting down MySQL..[ OK ]Starting MySQL..[ OK ]

Slave 上创建相同库:

create database if not exists roncoo default charset utf8 collate utf8_general_ci;use roncoo;

导入数据

[root@edu-mysql-02 ~]# mysql -uroot -p roncoo < /tmp/edu-master-roncoo.sqlEnter password:[root@edu-mysql-02 ~]#

8、登录 Slave 数据库,添加相关参数

(Master 的 IP、端口、同步用户、密码、position 号、读取哪个日志文件)

[root@edu-mysql-02 ~]# mysql -uroot -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 3Server version: 5.6.26-log Source distributionCopyright (c) 2000, 2015, 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.//通过那个用户作为主节点,密码是多少192.168.1.205  repl roncoo.123 端口, 日志文件mysql> change master to master_host='192.168.1.205', master_user='repl', master_password='roncoo.123', master_port=3306, master_log_file='edu-mysql- bin.000001 ' , master_log_pos=1389, master_connect_retry=30;Query OK, 0 rows affected, 2 warnings (0.01 sec)

上面执行的命令的解释:

master_host='192.168.1.205'## Master 的 IP 地址master_user='repl'## 用于同步数据的用户(在 Master 中授权的用户)master_password='roncoo.123'## 同步数据用户的密码master_port=3306## Master 数据库服务的端口//注意下面两个配置master_log_file='edu-mysql-bin.000001' ##指定 Slave 从哪个日志文件开始读复制数据(可 在 Master 上使用 show master status 查看到日志文件名)//主节点数据发生变化之后,position会发生变化,从节点只需要从position的地方开始读取 master_log_pos=429 ## 从哪个 POSITION 号开始读master_connect_retry=30 ##当重新建立主从连接时,如果连接建立失败,间隔多久后重试。 单位为秒,默认设置为 60 秒,同步延迟调优参数。## 查看主从同步状态mysql> show slave status\G;可看到 Slave_IO_State 为空, Slave_IO_Running 和 Slave_SQL_Running 是 No,表明 Slave 还 没有开始复制过程。## 开启主从同步mysql> start slave;Query OK, 0 rows affected (0.00 sec)## 再查看主从同步状态mysql> show slave status\G;

主要看以下两个参数,这两个参数如果是 Yes 就表示主从同步正常

Slave_IO_Running: YesSlave_SQL_Running: Yes

由截图中的主从同步状态信息可以看出,我们配置的主从同步是正常的。

可查看 master 和 slave 上线程的状态。在 master 上,可以看到 slave 的 I/O 线程创建的连接:

Master : mysql> show processlist\G;

1.row 为处理 slave 的 I/O 线程的连接。

2.row 为处理 MySQL 客户端连接线程。

3.row 为处理本地命令行的线程。

Slave : mysql> show processlist\G;

1.row 为 I/O 线程状态。

2.row 为 SQL 线程状态。

3.row 为处理本地命令行的线程。

9、主从数据复制同步测试

(1) 在 Master 中的 roncoo 库上变更数据的同步测试;

mysql> INSERT INTO `edu_user` VALUES (4,'同步测试 1','123456'),(5,'同步测试 2','123456');

Master 中添加完之后,登录 Slave 中查看数据是否已同步。

(2) 在 Master 上新建一个 ron 库

mysql> create database if not exists ron default charset utf8 collate utf8_general_ci;

在 Slave 中查看数据库

mysql> show databases;

最终的测试结果是,在 Master 中的操作,都成功同步到了 Slave。

10、测试过程中,如果遇到同步出错,可在 Slave 上重置主从复制设置(选操作):

(1) mysql> reset slave;(2) mysql> change master to master_host='192.168.1.205',master_user='repl',master_password='roncoo.123', master_port=3306, master_log_file='edu-mysql-bin.00000x',master_log_pos=xx,master_connect_retry=30;

(此时,master_log_file 和 master_log_pos 要在 Master 中用 show master status 命令查看)

注意:如果在 Slave 没做只读控制的情况下,千万不要在 Slave 中手动插入数据,那样数据 就会不一致,主从就会断开,就需要重新配置了。

11、上面所搭建的是单向复制的主从,也是用的比较多的,而双向主从其实就是 Master 和 Slave 都开启日志功能,然后在 Master 执行授权用户(这里授权的是自己作为从服务器,也 就是这里的 IP 地址是 Master 的 IP 地址),然后再在 Master 上进行 chang master 操作。

MySQL 主从数据同步延迟问题的调优

基于局域网的 Master/Slave 机制在通常情况下已经可以满足“实时”备份的要求了。如果延 迟比较大,可以从以下几个因素进行排查:

(1) 网络延迟;

(2) Master 负载过高;

(3) Slave 负载过高;

一般的做法是使用多台 Slave 来分摊读请求,再单独配置一台 Slave 只作为备份用,不进行 其他任何操作,就能相对最大限度地达到“实时”的要求了。

两个可以减少主从复制延迟的参数( 按需配置):

MySQL 可以指定 3 个参数,用于复制线程重连主库:–master-retry-count,–master-connect- retry,–slave-net-timeout 。其中 master-connect-retry 和 master-retry-count 需要在 Change Master 搭建主备复制时指定,而 slave-net-timeout 是一个全局变量,可以在 MySQL 运行 时在线设置。具体的重试策略为:备库过了 slave-net-timeout 秒还没有收到主库来的数据, 它就会开始第一次重试。然后每过 master-connect-retry 秒,备库会再次尝试重连主库。直 到重试了 master-retry-count 次,它才会放弃重试。如果重试的过程中,连上了主库,那么 它认为当前主库是好的,又会开始 slave-net-timeout 秒的等待。slave-net-timeout 的默认值 是 3600 秒,master-connect-retry 默认为 60 秒,master-retry-count 默认为 86400 次。也 就是说,如果主库一个小时都没有任何数据变更发送过来,备库才会尝试重连主库。这就是 为什么在我们模拟的场景下,一个小时后,备库才会重连主库,继续同步数据变更的原因。 这样的话,如果你的主库上变更比较频繁,可以考虑将 slave-net-timeout 设置的小一点,避 免主库 Binlog dump 线程终止了,无法将最新的更新推送过来。当然 slave-net-timeout 设 置的过小也有问题,这样会导致如果主库的变更确实比较少的时候,备库频繁的重新连接主 库,造成资源浪费。

slave-net-timeout=seconds

参数说明:当 Slave 从 Master 数据库读取 log 数据失败后,等待多久重新建立连接并获取数 据,单位为秒,默认设置为 3600 秒。

在做 MySQL Slave 的时候经常会遇到很多错误,需要根据具体原因跨过错误继续同步,但有 时候是因为网络不稳定、网络闪断造成同步不正常,如果 Slave 机器非常多的情况下,一个 一个登录服务器去 stop slave、start slave 变得无聊而且重复。从 MySQL5.1 开始支持的解决 方案配置:

master-connect-retry=seconds 参数说明:在主服务器宕机或连接丢失的情况下,从服务器线程重新尝试连接主服务器之前 睡眠的秒数。如果主服务器.info 文件中的值可以读取则优先使用。如果未设置,默认值为 60。 通常配置以上 2 个参数可以减少网络问题导致的主从数据同步延迟。 一般网络问题的错误是:

[ERROR] Error reading packet from server: Lost connection to MySQL server during query (server_errno=xxxx)[ERROR] Slave I/O thread: Failed reading log event, reconnecting to retry, log ‘edu-mysql- bin.000256’ position 23456

推荐参考链接:

http://www.it165.net/database/html/201311/4851.html http://blog.csdn.net/hguisu/article/details/7325124 http://www.woqutech.com/?p=1116 http://blog.chinaunix.net/uid-10661836-id-4116 512.html http://my.oschina.net/cimu/blog/165019 http://linuxguest.blog.51cto.com/195664/686813/ http://blog.itpub.net/29096438/viewspace-1409405/ http://blog.csdn.net/lxpbs8851/article/details/38455223 http://blog.csdn.net/seteor/article/details/17264633

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,953
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,477
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,290
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,107
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,739
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,773