MySQL主从复制

主从服务器分别作以下操作

1.版本一致
2.初始化表,并在后台启动MySQL
3.修改root的密码

修改主服务器Master

修改/etc/my.cnf

[mysqld]
       log-bin=mysql-bin  //[必须]启用二进制日志
       server-id=222      //[必须]服务器唯一ID,默认是1,一般取IP最后一段

修改从服务器Slave

修改/etc/my.cnf

[mysqld]
       log-bin=mysql-bin  //[不是必须]启用二进制日志
       server-id=226      //[必须]服务器唯一ID,默认是1,一般取IP最后一段

重启两台服务器的MySQL

在主服务器上建立帐户并授权Slave

mysql> GRANT REPLICATION SLAVE ON . to ‘sync’@’%’ identified by ‘password’;

登录主服务器的MySQL,查询Master的状态

mysql> show master status;
+------------------+-----------+--------------+------------------+
| File             | Position  | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+-----------+--------------+------------------+
| mysql-bin.000006 | 417323452 |              |                  |
+------------------+-----------+--------------+------------------+
1 row in set (0.00 sec)

执行完此步骤后不要再操作主服务器MySQL,防止主服务器状态值变化

配置从服务器Slave

mysql> change master to
    -> master_host='127.0.0.1',
    -> master_port=3307,
    -> master_user='sync',
    -> master_password='password',
    -> master_log_file='mysql-bin.000006',
    -> master_log_pos=417323452;

启动和停止Slave

slave start;
slave stop;

检查从服务器复制功能状态

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 127.0.0.1
                  Master_User: sync
                  Master_Port: 3307
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000006
          Read_Master_Log_Pos: 417393896
               Relay_Log_File: Krypt-relay-bin.000003
                Relay_Log_Pos: 2920792
        Relay_Master_Log_File: mysql-bin.000006
             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: 417393896
              Relay_Log_Space: 3396416
              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: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 61795
1 row in set (0.00 sec)

Slave_IO及Slave_SQL进程必须正常运行,即Yes状态,否则都是错误的状态(如:其中一个No均属错误)

最后,主从服务器测试

来源:http://369369.blog.51cto.com/319630/790921