search
HomeDatabaseMysql TutorialMysql主从复制技术(亲测)_MySQL

bitsCN.com

Mysql主从复制技术(亲测)

 

开始配置:  

    第一步:创建复制帐号 

        每个slave使用标准的MySQL用户名和密码连接master。进行复制操作的用户会授予
REPLICATIONSLAVE权限。 

     用户名的密码都会存储在文本文件master.info中。假如,你想创建repl用户,如下 

    mysql> GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO repl@'192.
168.1.%' IDENTIFIED BY '123456'; 

    第二步:配置My.cnf 

    配置Master的My.cnf,该文件默认位置为/etc/my.cnf 

 

        接下来对master进行配置,包括打开二进制日志,指定唯一的servr ID。例如,在配置文件
加入如下值: 

        [mysqld] 

        server-id=1 

        log-bin=mysql-bin 

 

        重启mysql,service mysql restart , 

        登录mysql -uroot -p 

        运行SHOW MASTER STATUS,输出如下: 

+------------------+----------+--------------+------------------+ 

        | File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | 

        +------------------+----------+--------------+------------------+ 

        | mysql-bin.000002 |      106 |              |                  | 

        +------------------+----------+--------------+------------------+ 

        1 row in set (0.00 sec) 

 

    配置Slave的My.cnf,该文件默认位置为/etc/my.cnf 

        Slave的配置与master类似,你同样需要重启slave的MySQL。如下:  

        server-id = 2 

        log-bin = mysql-bin 

        relay_log = mysql-relay-bin  

        log_slave_updates = 1  

        read_only = 1  

        server-id是必须的,而且唯一。slave没有必要开启二进制日志,但是在一些情况下,必须
设置,例如,如果slave为其它slave的master,必须设置bin_log。在这里,我们开启了二进制
日志,而且显示的命名(默认名称为hostname,但是,如果hostname改变则会出现问题)。  

relay_log配置中继日志,log_slave_updates表示slave将复制事件写进自己的二进制日志(后面会
看到它的用处)。 

有些人开启了slave的二进制日志,却没有设置log_slave_updates,然后查看slave的数据是否改
变,这是一种错误的配置。所以,尽量使用read_only,它防止改变数据(除了特殊的线程)。但是,
read_only并是很实用,特别是那些需要在slave上创建表的应用。 

        重启mysql,service mysql restart , 

        登录mysql -uroot -p 

 

    第三步:启动slave 

        接下来就是让slave连接master,并开始重做master二进制日志中的事件。你不应该用配置
文件进行该操作,而应该使用CHANGE MASTER TO语句,该语句可以完全取代对配置文件的修改,
而且它可以为slave指定不同的master,而不需要停止服务器。如下: 

        mysql>CHANGE MASTER TO MASTER_HOST='192.168.60.73',MASTER_USER='repl',MASTER_PASSWORD='123456',MASTER
_LOG_FILE='mysql-bin.000002',MASTER_LOG_POS=0; 

        MASTER_LOG_POS的值为0,因为它是日志的开始位置。然后,你可以用SHOW SLAVE STATUS
语句查看slave的设置是否正确: 

        mysql> SHOW SLAVE STATUS/G 

*************************** 1. row *************************** 

             Slave_IO_State: 

                Master_Host: server1 

                Master_User: repl 

                Master_Port: 3306 

              Connect_Retry: 60 

             Master_Log_File: mysql-bin.000001 

             Read_Master_Log_Pos: 4 

             Relay_Log_File: mysql-relay-bin.000001 

              Relay_Log_Pos: 4 

             Relay_Master_Log_File: mysql-bin.000001 

            Slave_IO_Running: No 

            Slave_SQL_Running: No 

                             ...omitted... 

        Seconds_Behind_Master: NULL 

        Slave_IO_State, Slave_IO_Running, 和Slave_SQL_Running表明slave还没有开始复制过程。
日志的位置为4而不是0,这是因为0只是日志文件的开始位置,并不是日志位置。实际上,MySQL知
道的第一个事件的位置是4。 

 

为了开始复制,你可以运行: 

mysql> START SLAVE; 

mysql> SHOW SLAVE STATUS/G 

运行SHOW SLAVE STATUS查看输出结果: 

*************************** 1. row *************************** 

        Slave_IO_State: Waiting for master to send event 

                Master_Host: server1 

                Master_User: repl 

                Master_Port: 3306 

               Connect_Retry: 60 

               Master_Log_File: mysql-bin.000001 

               Read_Master_Log_Pos: 164 

              Relay_Log_File: mysql-relay-bin.000001 

              Relay_Log_Pos: 164 

              Relay_Master_Log_File: mysql-bin.000001 

              Slave_IO_Running: Yes 

              Slave_SQL_Running: Yes 

                             ...omitted... 

      Seconds_Behind_Master: 0 

注意,slave的I/O和SQL线程都已经开始运行,而且Seconds_Behind_Master不再是NULL。日志
的位置增加了,意味着一些事件被获取并执行了。如果你在master上进行修改,你可以在slave上看
到各种日志文件的位置的变化,同样,你也可以看到数据库中数据的变化。 

 

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

 

mysql> show processlist /G 

*************************** 1. row *************************** 

     Id: 1 

   User: root 

   Host: localhost:2096 

     db: test 

Command: Query 

   Time: 0 

 State: NULL 

   Info: show processlist 

*************************** 2. row *************************** 

     Id: 2 

   User: repl 

   Host: localhost:2144 

     db: NULL 

Command: Binlog Dump 

   Time: 1838 

 State: Has sent all binlog to slave; waiting for binlog to be updated 

   Info: NULL 

2 rows in set (0.00 sec) 

基本到这里就完成,至于后期的加强操作,我会在另行添加。 

Mysql复制的时候可以做到限制复制(主) 

binlog-do-db=work      #只复制 

binlog_ignore_db=mysql    #不允许复制 

  

Replicate_Do_DB=mysql 

replicate-ignore-db=mysql 

另外还有几条常用的命令 

flush mater;  #清除垃圾 

flush slave;  #清除垃圾 

start slave;  #开始服务 

reset slave;  #重设服务 

stop slave;   #停止服务 

  

上面复制方式是假设在新设Master和slave的情况下,实际环境并不十分实用,例如,你在一
组运行了很久的Master中加入一个新的slave呢? 

这样我们就需要优先进行数据处理。 

1.现将Master的数据库锁定,以免数据复制的时候出现差异。 

FLUSH TABLES WITH READ LOCK; 

2. 在另一个连接用mysqldump创建一个你想进行复制的数据库的转储: 

shell> mysqldump --all-databases --lock-all-tables >dbdump.db 

3. 对表释放锁。  

mysql> UNLOCK TABLES; 

上面方法中,第2部需要将数据库复制到新slave中还原,这样,Master和新Slave的数据源就一致。 

其实第2部的方法有很多,也可以使用Mysql软件进行同步,例如:Navicat for Mysql  

方法不是唯一,只要结果一致即可。 

4.完成旧数据同步后,Master中输入

mysql> show master status; 

##得到: 

+------------------+----------+--------------+---------------------------+ 

| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB          | 

+------------------+----------+--------------+---------------------------+ 

| mysql-bin.000024 |    38113 |              | mysql,test | 

 

1 row in set (0.00 sec) 

5.然后在根据上表中内容输入上文启动Slave步骤的内容。 

CHANGE MASTER TO MASTER_HOST='192.168.60.73',MASTER_USER='repl',MASTER_PASSWORD='123456',
MASTER_LOG_FILE='mysql-bin.000002',MASTER_LOG_POS=0; 

6.启动slave 

START SLAVE; 

7.启动完成后进行检查。 

mysql> SHOW SLAVE STATUS/G                                                        ***************************
1. row *************************** 

               Slave_IO_State: Waiting for master to send event 

                  Master_Host: 192.168.1.171 

                  Master_User: repl 

                  Master_Port: 3306 

                Connect_Retry: 60 

              Master_Log_File: mysql-bin.000024 

              Read_Master_Log_Pos: 38255 

               Relay_Log_File: mysql-relay-bin.000002 

                Relay_Log_Pos: 393 

              Relay_Master_Log_File: mysql-bin.000024 

             Slave_IO_Running: Yes 

            Slave_SQL_Running: Yes 

              Replicate_Do_DB: 

          Replicate_Ignore_DB: mysql,wdcpdb,mysql,wdcpdb 

           Replicate_Do_Table: 

       Replicate_Ignore_Table: 

      Replicate_Wild_Do_Table: 

        Replicate_Wild_Ignore_Table: 

                   Last_Errno: 0 

                   Last_Error: 

                 Skip_Counter: 0 

          Exec_Master_Log_Pos: 38255 

              Relay_Log_Space: 548 

              Until_Condition: None 

               Until_Log_File: 

                Until_Log_Pos: 0 

           Master_SSL_Allowed: No 

           Master_SSL_CA_File: 

           Master_SSL_CA_Path: 

             Master_SSL_Cert: 

            Master_SSL_Cipher: 

               Master_SSL_Key: 

        Seconds_Behind_Master: 0 

Master_SSL_Verify_Server_Cert: No 

          Last_IO_Errno: 0 

                Last_IO_Error: 

               Last_SQL_Errno: 0 

               Last_SQL_Error: 

1 row in set (0.00 sec) 

完成 

测试过程要主要的问题: 

 

1.请先配置好Mysql 

2.开通复制前请将Mysql的库和表的框架复制过去。

(在测试一下能不能连表都复制过去!) 

 

bitsCN.com
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: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use