首页 > 代码库 > mysql主从同步设置

mysql主从同步设置

1、主服务器地址:192.168.1.244

   从服务器地址:192.168.1.245

2、主服务器master设置

   1)修改/etc/my.cnf

      添加:

      log-bin = /home/mysql/log/mysql-bin.log

      server-id=244

      (注:主从server id不可重复,建议以IP地址设置)   

   2)登录mysql 

   创建用户sync并授权192.168.1.245

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

   查看主数据库状态

   Mysql> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 | 261 | | |
+------------------+----------+--------------+------------------+

记录下file与position的值,后面会用到。

3、从服务器设置

    1)修改/etc/my.cnf

        server-id=245

    2)登录mysql

     执行同步SQL语句
mysql> change master to
            master_host=’192.168.10.130’,
            master_user=’rep1’,
            master_password=’password’,
            master_log_file=’mysql-bin.000005’,
            master_log_pos=261; 

正确执行后启动Slave同步进程
mysql> start slave;

主从同步检查
mysql> show slave status\G
==============================================
**************** 1. row *******************
Slave_IO_State:
Master_Host: 192.168.1.244
Master_User: rep1
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000005
Read_Master_Log_Pos: 415
Relay_Log_File: localhost-relay-bin.000008
Relay_Log_Pos: 561
Relay_Master_Log_File: mysql-bin.000005
Slave_IO_Running: YES
Slave_SQL_Running: YES

Replicate_Do_DB:
……………省略若干……………
Master_Server_Id: 244
1 row in set (0.01 sec)
==============================================

至此服务器配置完成。

4、验证主从复制效果

主服务器操作:

mysql> create database first_db;
Query Ok, 1 row affected (0.01 sec)

在主服务器上创建表first_tb
mysql> create table first_tb(id int(3),name char(10));
Query Ok, 1 row affected (0.00 sec)

在主服务器上的表first_tb中插入记录
mysql> insert into first_tb values (001,’myself’);
Query Ok, 1 row affected (0.00 sec)


在从服务器上查看
mysql> show databases;
=============================
+--------------------+
| Database |
+--------------------+
| information_schema |
| first_db |
| mysql |
| performance_schema |
| test |
+--------------------+
5 rows in set (0.01 sec)
=============================
数据库first_db已经自动生成

mysql> use first_db
Database chaged

mysql> show tables;
=============================
+--------------------+
| Tables_in_first_db |
+--------------------+
| first_tb |
+--------------------+
1 row in set (0.02 sec)
=============================
数据库表first_tb也已经自动创建

mysql> select * from first_tb;
=============================
+------+------+
| id | name |
+------+------+
| 1 | myself |
+------+------+
1 rows in set (0.00 sec)
=============================
记录也已经存在



mysql主从同步设置