本文适用于新安装的主库和备库,假定主备库为空,如果你是从已存在的主库复制,请转到《[MySQL] 复制(3)- 创建主备复制(从另一个服务器开始复制)》
主库需要打开二进制日志,并制定一个唯一的server id,my.cnf文件中增加或修改如下内容:
server_id=60 log-bin = /data/mysql/log/mysql-bin
server_id=61 read_only=1 log_bin = /data/mysql/log/mysql-bin log_slave_updates = 1 relay_log = /data/mysql/log/mysqld-relay-bin
GRANT REPLICATION SLAVE ON *.* TO repluser@'192.168.1.%' IDENTIFIED BY 'replpwd';最好在备库里也创建这样一个用户,方便以后切换。
show master status; +------------------+----------+--------------+------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | +------------------+----------+--------------+------------------+ | mysql-bin.000003 | 245 | | | +------------------+----------+--------------+------------------+然后,在备库执行如下语句连接主库获取二进制日志:
change master to master_host='192.168.1.60', master_user='repluser', master_password='replpwd', master_log_file='mysql-bin.000003', master_log_pos=245;接着,在备库执行如下语句启动复制:
start slave下面是备库的状态:
show slave status\G *************************** 1. row *************************** Slave_IO_State: Waiting for master to send event Master_Host: 192.168.1.60 Master_User: repluser Master_Port: 3306 Connect_Retry: 60 Master_Log_File: mysql-bin.000003 Read_Master_Log_Pos: 647 Relay_Log_File: mysqld-relay-bin.000002 Relay_Log_Pos: 655 Relay_Master_Log_File: mysql-bin.000003 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: 647 Relay_Log_Space: 812 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: 60我们通过Slave_IO_Running和Slave_SQL_Running来判断备库是否和主库在同步。
show processlist\G Id: 9 User: repluser Host: 192.168.1.61:36722 db: NULL Command: Binlog Dump Time: 379 State: Master has sent all binlog to slave; waiting for binlog to be updated Info: NULL Rows_sent: 0 Rows_examined: 0 Rows_read: 2在备库上可以看到两个线程,分别是I/O线程和SQL线程:
show processlist\G Id: 10 User: system user Host: db: NULL Command: Connect Time: 615 State: Waiting for master to send event Info: NULL Rows_sent: 0 Rows_examined: 0 Rows_read: 1 *************************** 3. row *************************** Id: 11 User: system user Host: db: NULL Command: Connect Time: 907 State: Slave has read all relay log; waiting for the slave I/O thread to update it Info: NULL Rows_sent: 0 Rows_examined: 0 Rows_read: 1 3 rows in set (0.00 sec)