---
title: "MySQL数据库设置主从同步"
author: "neverforget"
date: "2015-03-14T22:43:49Z"
tags: []
categories: ["开源软件"]
slug: "mysql"
draft: false
lastmod: "2015-03-14T22:52:26Z"
id: 2192535
url: "https://never-forget.iteye.com/blog/2192535"
---

**主：**

```

Enter password: *******
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.1.73-community-log MySQL Community Server (GPL)

Copyright (c) 2000, 2013, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| am-example         |
| crm                |
| masterdb           |
| mysql              |
| test               |
+--------------------+
6 rows in set (0.00 sec)

mysql> use masterdb;
Database changed
mysql> select * from mastertable;
Empty set (0.07 sec)

mysql> insert into mastertable('1','ford');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near ''1','
ford')' at line 1
mysql> insert into mastertable(1,'ford');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '1,'fo
rd')' at line 1
mysql> insert into mastertable values ('1','ford');
Query OK, 1 row affected (0.10 sec)

mysql> insert into mastertable(2,'Jon');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '2,'Jo
n')' at line 1
mysql> insert into mastertable values ('2','Jon');
Query OK, 1 row affected (0.11 sec)

mysql> select * from mastertable;
+------+------+
| id   | name |
+------+------+
|    1 | ford |
|    2 | Jon  |
+------+------+
2 rows in set (0.00 sec)

mysql> select * from mastertable;
+------+------+
| id   | name |
+------+------+
|    1 | ford |
|    2 | Jon  |
+------+------+
2 rows in set (0.00 sec)

mysql> delete from mastertable where id=1;
Query OK, 1 row affected (0.13 sec)

mysql> delete from mastertable where id=2;
Query OK, 1 row affected (0.15 sec)

mysql>

```


**从：**

```

[root@localhost etc]# vi my.cnf
[root@localhost etc]# service mysql stop
Shutting down MySQL.... SUCCESS!
[root@localhost etc]# service mysql start
Starting MySQL.... SUCCESS!
[root@localhost etc]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.73-community-log MySQL Community Server (GPL)

Copyright (c) 2000, 2013, 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> change master to master_host='192.168.2.39',master_user='slave_account',master_password='123456',master_log_file='mysql-bin.000001',master_log_pos=332;
Query OK, 0 rows affected (0.39 sec)

mysql> start slave;
Query OK, 0 rows affected (0.09 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.2.39
                  Master_User: slave_account
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 332
               Relay_Log_File: localhost-relay-bin.000002
                Relay_Log_Pos: 251
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           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: 332
              Relay_Log_Space: 410
              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)

ERROR:
No query specified

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| test               |
+--------------------+
3 rows in set (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| masterdb           |
| mysql              |
| test               |
+--------------------+
4 rows in set (0.00 sec)

mysql> use masterdb;
Database changed
mysql> show tables;
+--------------------+
| Tables_in_masterdb |
+--------------------+
| mastertable        |
+--------------------+
1 row in set (0.00 sec)

mysql> select * from mastertable;
Empty set (0.06 sec)

mysql> select * from mastertable;
+------+------+
| id   | name |
+------+------+
|    1 | ford |
|    2 | Jon  |
+------+------+
2 rows in set (0.00 sec)

mysql> delete from mastertable where id=1;
Query OK, 1 row affected (0.05 sec)

mysql> select * from mastertable;
+------+------+
| id   | name |
+------+------+
|    2 | Jon  |
+------+------+
1 row in set (0.00 sec)

mysql> select * from mastertable;
+------+------+
| id   | name |
+------+------+
|    2 | Jon  |
+------+------+
1 row in set (0.00 sec)

mysql> select * from mastertable;
Empty set (0.00 sec)

mysql> select * from mastertable;
Empty set (0.00 sec)

```



**最后一定要记得打开从的只读：**
主从复制中容易出现的问题：

1.限制从服务器只读，保证主从数据一致。

    show global variables like ‘%read%‘

    更改slave的全局服务器变量read_only为on

    set global read_only on

    从节点上授权只读 set global read_only = 1;如果永久有效更改mysql的my.ini 或my.cnf，在 中设置read_only = 1

2.保证主从复制时的事务安全

    如果mysql比较繁忙它会把二进制日志缓存在内存中，不繁忙时才会把他写到磁盘中，前提就是mysql对二进制日志事件数据会缓冲。在master上设置如下参数 set global  sync_binlog = 1 事物一提交，就必须同步二进制日志，这样会降低性能，但是数据非常重要的情况下。

------------------------------------------------------------
MYSQL主从同步是目前使用比较广泛的数据库架构，技术比较成熟，配置也不复杂，特别是对于负载比较大的网站，主从同步能够有效缓解数据库读写的压力。

MySQL主从同步的机制
MYSQL主从同步是在MySQL主从复制(Master-Slave Replication)基础上实现的，通过设置在Master MySQL上的binlog(使其处于打开状态)，Slave MySQL上通过一个I/O线程从Master MySQL上读取binlog，然后传输到Slave MySQL的中继日志中，然后Slave MySQL的SQL线程从中继日志中读取中继日志，然后应用到Slave MySQL的数据库中。这样实现了主从数据同步功能。


![](http://dl2.iteye.com/upload/attachment/0106/6646/f38443c0-2a07-3f71-b44d-d7fc52daa0ab.jpg)

MySQL主从同步的作用
1、可以作为一种备份机制，相当于热备份
2、可以用来做读写分离，均衡数据库负载
MySQL主从同步的步骤
一、准备操作
1、主从数据库版本一致，建议版本5.5以上
2、主从数据库数据一致
二、主数据库master修改

1、修改MySQL配置：

 view plaincopy在CODE上查看代码片派生到我的代码片
# 日志文件名  
log-bin = mysql-bin  
  
# 主数据库端ID号  
server-id = 1  
2、重启mysql，创建用于同步的账户：
 view plaincopy在CODE上查看代码片派生到我的代码片
# 创建slave帐号slave_account，密码123456  
mysql>grant replication slave on *.* to 'slave_account'@'%' identified by '123456';  
  
# 更新数据库权限  
mysql>flush privileges;  
3、查询master的状态

 view plaincopy
mysql> show master status;  
+------------------+----------+--------------+------------------+  
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |  
+------------------+----------+--------------+------------------+  
| mysql-bin.000009 |      196 |              |                  |  
+------------------+----------+--------------+------------------+  
1 row in set  
 注：执行完这个步骤后不要再操作主数据库了，防止主数据库状态值变化
三、从数据库slave修改
1、修改MySQL配置：

 view plaincopy在CODE上查看代码片派生到我的代码片
# 从数据库端ID号  
server-id =2  
2、执行同步命令
 view plaincopy在CODE上查看代码片派生到我的代码片
# 执行同步命令，设置主数据库ip，同步帐号密码，同步位置  
mysql>change master to master_host='192.168.1.2',master_user='slave_account',master_password='123456',master_log_file='mysql-bin.000009',master_log_pos=196;  
  
# 开启同步功能  
mysql>start slave;  
3、检查从数据库状态：

 view plaincopy
mysql> show slave status\G;  
*************************** 1. row ***************************  
               Slave_IO_State: Waiting for master to send event  
                  Master_Host: 192.168.1.2  
                  Master_User: slave_account  
                  Master_Port: 3306  
                Connect_Retry: 60  
              Master_Log_File: mysql-bin.000009  
          Read_Master_Log_Pos: 196  
               Relay_Log_File: vicky-relay-bin.000002  
                Relay_Log_Pos: 253  
        Relay_Master_Log_File: mysql-bin.000009  
             Slave_IO_Running: Yes  
            Slave_SQL_Running: Yes  
              Replicate_Do_DB:  
          Replicate_Ignore_DB:  
          ...  
注：Slave_IO_Running及Slave_SQL_Running进程必须正常运行，即YES状态，否则说明同步失败。
到这里，主从数据库设置工作已经完成，自己可以新建数据库和表，插入和修改数据，测试一下是否成功

四、其他可能用到的相关参数

1、master端：
 view plaincopy在CODE上查看代码片派生到我的代码片
# 不同步哪些数据库  
binlog-ignore-db = mysql  
binlog-ignore-db = test  
binlog-ignore-db = information_schema  
  
# 只同步哪些数据库，除此之外，其他不同步  
binlog-do-db = game  
  
# 日志保留时间  
expire_logs_days = 10  
  
# 控制binlog的写入频率。每执行多少次事务写入一次  
# 这个参数性能消耗很大，但可减小MySQL崩溃造成的损失  
sync_binlog = 5  
  
# 日志格式，建议mixed  
# statement 保存SQL语句  
# row 保存影响记录数据  
# mixed 前面两种的结合  
binlog_format = mixed  
2、slave端：

 view plaincopy
# 停止主从同步  
mysql> stop slave;  
  
# 连接断开时，重新连接超时时间  
mysql> change master to master_connect_retry=50;  
  
# 开启主从同步  
mysql> start slave;  
以上连接超时设置，类似方式可用于设置主数据库ip，同步帐号密码，同步位置

![](http://dl2.iteye.com/upload/attachment/0106/6648/d0939176-fb64-3fcd-90cf-2393cc88061c.jpg)