本文我們主要介紹MySQL Replication環境搭建的過程,以實現數據庫負載均衡。MySQL Replication環境搭建的具體過程如下:
環境:兩台ubuntu,一台做Master,一台Slave。
Master: ubuntub(192.168.1.101)
Slave: ubuntuc(192.168.1.104)
Master上的配置如下:
- ubuntub@ubuntub:/etc/mysql$ sudo vi my.cnf
- #bind-address = 127.0.0.1 //注釋掉
- server-id = 1 // 給master設置為1,給slave設置為2
- log_bin = /var/log/mysql/mysql-bin.log
- ubuntub@ubuntub:/etc/mysql$ sudo /etc/init.d/mysql restart
- ubuntub@ubuntub:/etc/mysql$ mysql -uroot -p
- mysql> GRANT REPLICATION SLAVE ON *.* TO 'rep_user'@'%' IDENTIFIED BY 'rep_password';
- mysql> FLUSH TABLES WITH READ LOCK;
- Query OK, 0 rows affected (0.00 sec)
- mysql> SHOW MASTER STATUS;
- +------------------+----------+--------------+------------------+
- | File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
- +------------------+----------+--------------+------------------+
- | mysql-bin.000001 | 261 |
- | |
- +------------------+----------+--------------+------------------+
- 1 row in set (0.02 sec)
- mysql> use rep;
- mysql> select * from user;
- +-------+----+
- | name | id |
- +-------+----+
- | B | 1 |
- | user3 | 2 |
- +-------+----+
- 2 rows in set (0.00 sec)
- ubuntub@ubuntub:/data/mysql_bak$ mysqldump -uroot -p rep > dbdump.sql
- ubuntub@ubuntub:/data/mysql_bak$ mysql -u root -p
- mysql> UNLOCK TABLES;
- ubuntub@ubuntub:/data/mysql_bak$ scp /data/mysql_bak/dbdump.sql [email protected]:/data/ //把備份數據倒倒slave上
在Slave上的配置:
- ubuntuc@ubuntuc:/data$ sudo vi /etc/mysql/my.cnf
- #bind-address = 127.0.0.1
- server-id = 2
- log_bin = /var/log/mysql/mysql-bin.log
- ubuntuc@ubuntuc:/etc/mysql$ sudo /etc/init.d/mysql restart
- ubuntuc@ubuntuc:/data$ mysql -u root -p
- mysql> use rep;
- mysql> source /data/dbdump.sql //把數據導入
- mysql> CHANGE MASTER TO //Change Master
- -> MASTER_HOST='192.168.1.101',
- -> MASTER_USER='rep_user',
- -> MASTER_PASSWORD='rep_password',
- -> MASTER_LOG_FILE='mysql-bin.000001',
- -> MASTER_LOG_POS=261;
- mysql> START SLAVE;
- mysql> show master status;
- +------------------+----------+--------------+------------------+
- | File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
- +------------------+----------+--------------+------------------+
- | mysql-bin.000002 | 746 |
- | |
- +------------------+----------+--------------+------------------+
- mysql> show slave status; //查看一下沒有錯誤,比如server-id有沖突的話,可能會導致一些錯誤。
測試:
1)在Master上創建一個數據庫,然後在Slave上查看,show databases; 應該是可以看到;
2) Master上對rep數據庫的user表進行操作,結果立即復制倒slave上;
關於MySQL Replication環境搭建的知識就介紹到這裡,如果您想了解更多關於MySQL數據庫的知識,可以看一下這裡的文章:http://database.51cto.com/mysql/,相信一定會帶給您收獲的!