search
HomeDatabaseMysql Tutorialmysql主从同步中应注意的问题_MySQL

MYSQL主从同步的作用

 

(1) 数据分布

 

(2) 负载平衡(load balancing)

 

(3) 备份

 

(4) 高可用性(high availability)和容错

 

MYSQL主从同步的原理

 

关于MYSQL的主从同步,最主要的是要了解MYSQL的主从同步是如何工作的也即主从同步的原理,通过下图能很明白的指导其工作的过程:

mysql主从同步中应注意的问题_MySQL

大致描述一下过程:从服务器的IO线程从主服务器获取二进制日志,并在本地保存为中继日志,然后通过SQL线程来在从上执行中继日志中的内容,从而使从库和主库保持一致。主从同步的详细过程如下:

 

1. 主服务器验证连接。

 

2. 主服务器为从服务器开启一个线程。

 

3. 从服务器将主服务器日志的偏移位告诉主服务器。

 

4. 主服务器检查该值是否小于当前二进制日志偏移位。

 

5.  如果小于,则通知从服务器来取数据。

 

6.  从服务器持续从主服务器取数据,直至取完,这时,从服务器线程进入睡眠,主服务器线程同时进入睡眠。

 

7. 当主服务器有更新时,主服务器线程被激活,并将二进制日志推送给从服务器,并通知从服务器线程进入工作状态。

 

8. 从服务器SQL线程执行二进制日志,随后进入睡眠状态。

 

MYSQL主从同步的搭建实战

 

主从同步的搭建是一项比较细的技术活,前期做好了一些事情会让你在以后的工作中减少很多工作,搭建的时候需要注意一些问题,一会搭建的时候会一边搭建一边介绍需要注意的问题,让初学者能在刚开始的时候就有效的规避掉一些潜在的问题(MYSQL安装这里不做介绍):

 

1.  主从同步环境介绍

操作系统环境:Centos 5.5 64 bit

MYSQL版本:MYSQL 5.1.50

主服务器的IP:10.1.1.75

从服务器的IP:10.1.1.76

 

2.   在主服务器上建立同步帐号

GRANT REPLICATION SLAVE,FILE ON *.* TO 'replication'@'10.1.1.%' IDENTIFIED BY '123456';

FLUSH PRIVILEGES;

 

注意:大家在设置权限的时候不要将密码设置过于简单!

 

3.   从服务器配置文件的更改

server-id = 2

replicate-wild-ignore-table=mysql.%

log-slave-updates  #这个有需要可以开启

 

注意:

 

server-id这一项需要认真检查,一定不能和主服务器冲突了,不然到时候会出现莫民其妙的问题,因为同步的时候会会根据server-id做判断,如果server-id一样就不进行同步了,不然可能会导致死循环(主主同步或者环状同步的时候)。

 

有的人会感觉奇怪我这里为什么要使用replicate-wild-ignore-table参数,而不是用replicate-do-db或者replicate-ignore-db来过滤需要同步的数据库和不需要同步的数据库。这里有几个原因:

 

replicate-wild-ignore-table参数能同步所有跨数据库的更新,比如replicate-do-db或者replicate-ignore-db不会同步类似

use mysql;

UPDATE test.aaa SET amount=amount+10;

 

B. replicate-wild-ignore-table=mysql.%在以后需要添加同步数据库的时候能方便添加而不需要重新启动从服务器的数据库。因为以后很可能需要同步其他的数据库。

 

3) auto_increment_increment和auto_increment_offset参数,这 两个参数一般用在主主同步中,用来错开自增值, 防止键值冲突。

 

4)  --slave-skip-errors参数,不要胡乱使用这些跳过错误的参数,除非你非常确定你在做什么。当你使用这些参数时候,MYSQL会忽略那些错误,这样会导致你的主从服务器数据不一致。

 

4.  从主服务器得到一个快照版本

 

如果你的是MYISAM或者既有MYISAM又有INNODB的话就在主服务器上使用如下命令导出服务器的一个快照:

mysqldump -uroot -p --lock-tables --events --triggers --routines --flush-logs --master-data=2 --databases test > db.sql

试过只有INNODB的话就是用如下命令:

mysqldump -uroot -p --single-transaction --events --triggers --routines --flush-logs --master-data=2 --databases test > db.sql

 

这里需要注意几个参数的使用:

--single-transaction 这个参数只对innodb适用。

--databases 后面跟除mysql以后的其他所有数据库的库名,我这里只有一个test库。

--master-data 参数会记录导出快照时候的mysql二进制日志位置,一会会用到。

 

5.  将快照版本还原到从服务器上

mysqldump -uroot -p -h 10.1.1.76 test

 

将快照版本还原到从服务器上以后,此时从服务器上的数据和主服务器的数据是一致的。

 

6.  在从服务器上使用change master从主服务器上同步

 

使用grep命令查找到二进制日志的名称以及位置

[root@ns1 ~]# grep -i "change master" db.sql

-- CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000006', MASTER_LOG_POS=106;

生成CHANGE MASTER语句,然后在从上执行

STOP SLAVE; 

CHANGE MASTER TO MASTER_HOST='10.1.1.75',MASTER_USER='replication',MASTER_PASSWORD='123456',MASTER_LOG_FILE='mysql-bin.000006', MASTER_LOG_POS=106;

START SLAVE;

这样就完成了主从同步的搭建,最后使用SHOW SLAVE STATUS\G;查看Slave_IO_Running和Slave_SQL_Running的状态,如果都为Yes,就大功告成了。

 

注意:不要将同步的信息写入配置文件中,不方便管理,尤其是有变动需要重启。

 

MYSQL主从同步的管理

这里介绍一些管理MYSQL主从同步的命令:

1.  停止MYSQL同步

STOP SLAVE IO_THREAD;    #停止IO进程

STOP SLAVE SQL_THREAD;    #停止SQL进程

STOP SLAVE;                               #停止IO和SQL进程

2.  启动MYSQL同步

START SLAVE IO_THREAD;    #启动IO进程

START SLAVE SQL_THREAD;  #启动SQL进程

START SLAVE;                             #启动IO和SQL进程

3.   重置MYSQL同步

RESET SLAVE;

 

用于让从属服务器忘记其在主服务器的二进制日志中的复制位置, 它会删除master.info和relay-log.info文件,以及所有的中继日志,并启动一个新的中继日志,当你不需要主从的时候可以在从上执行这个操作。不然以后还会同步,可能会覆盖掉你的数据库,我以前就遇到过这样傻叉的事情。哈哈!

 

4.   查看MYSQL同步状态

 

SHOW SLAVE STATUS;

 

这个命令主要查看Slave_IO_Running、Slave_SQL_Running、Seconds_Behind_Master、Last_IO_Error、Last_SQL_Error这些值来把握复制的状态。

 

5.  临时跳过MYSQL同步错误

 

经常会朋友mysql主从同步遇到错误的时候,比如一个主键冲突等,那么我就需要在确保那一行数据一致的情况下临时的跳过这个错误,那就需要使用SQL_SLAVE_SKIP_COUNTER = n命令了,n是表示跳过后面的n个事件,比如我跳过一个事件的操作如下:

STOP SLAVE;

SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;

START SLAVE;

 

6.  从指定位置重新同步

 

有的时候主从同步有问题了以后,需要从log位置的下一个位置进行同步,相当于跳过那个错误,这时候也可以使用CHANGE MASTER命令来处理,只要找到对应的LOG位置就可以,比如:

CHANGE MASTER TO MASTER_HOST='10.1.1.75',MASTER_USER='replication',MASTER_PASSWORD='123456',MASTER_LOG_FILE='mysql-bin.000006', MASTER_LOG_POS=106;

START SLAVE;

 

MYSQL主从同步的管理经验介绍

 

1.   不要乱使用SQL_SLAVE_SKIP_COUNTER命令。

 

这个命令跳过之后很可能会导致你的主从数据不一致,一定要先将指定的错误记录下来,然后再去检查数据是否一致,尤其是核心的业务数据。

 

2.   结合percona-toolkit工具pt-table-checksum定期查看数据是否一致。

 

这个是DBA必须要定期做的事情,呵呵,有合适的工具何乐而不为呢?另外percona-toolkit还提供了对数据库不一致的解决方案,可以采用pt-table-sync,这个工具不会更改主的数据。还可以使用pt-heartbeat来查看从服务器的复制落后情况。

 

3.   使用replicate-wild-ignore-table选项而不要使用replicate-do-db或者replicate-ignore-db。

 

原因已经在上面做了说明。

 

4.   将主服务器的日志模式调整成mixed。

 

5.   每个表都加上主键,主键对数据库的同步会有影响尤其是居于ROW复制模式。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

What are common causes of poor MySQL query performance?What are common causes of poor MySQL query performance?Apr 12, 2025 am 12:11 AM

The main reasons for poor MySQL query performance include not using indexes, wrong execution plan selection by the query optimizer, unreasonable table design, excessive data volume and lock competition. 1. No index causes slow querying, and adding indexes can significantly improve performance. 2. Use the EXPLAIN command to analyze the query plan and find out the optimizer error. 3. Reconstructing the table structure and optimizing JOIN conditions can improve table design problems. 4. When the data volume is large, partitioning and table division strategies are adopted. 5. In a high concurrency environment, optimizing transactions and locking strategies can reduce lock competition.

When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function