那麼Mysql 能不能實現兩個系統之間通過TCP/IP去複製數據庫?能不能實現實時複製呢?也就是說能不能實現同步(Synchronization)的問題。先概括介紹一下Mysql 的Replication Database功能。
複製(Replication)類似於拷貝數據庫到另一臺服務器上,但它是通過定義Master 和Slave的關係去實時地保證兩個數據庫的完全同步。這個功能在Mysql的3.23版中開始出現。
下面大家一起來測試一下Mysql的Replication 功能。
作者的平臺是:
Slave: Mysql 3.23.56-log on FreeBSD 4.8 Stable IP:192.168.10.200
/usr/local/mysql/bin
MasterBSD#./mysql –u root –p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or /g.
Your MySQL connection id is 2 to server version: 3.23.53-log
Type 'help;' or '/h' for help. Type '/c' to clear the buffer.
mysql> GRANT FILE ON *.* TO [email protected] IDENTIFIED BY ‘repplication’;
然後打包要複製的數據庫
MasterBSD# tar czvf repdatabase.tar.gz repdatabase
這樣,我們的到一個repdatabase數據庫的打包文件repdatabase.tar.gz
2設置主服務器Master的my.cnf,啓動Mysql服務log-bin
server-id=1
sql-bin-update-same
binlog-do-db= repdatabase
然後把Master主服務器的Mysql重啓。
MasterBSD# /usr/local/mysql/bin/safe_mysqld --user=mysql &
剛纔我們在Master中打包了repdatabase.tar.gz,它的作用就是要在Slave恢復成一樣的數據庫。先把Master 的repdatabase.tar.gz文件傳到Slave機器中去。然後
master-user=replication
master-password=replication
master-port=3306
server-id=2
master-connect-retry=60
replicate-do-db=reldatabase [要更新的數據庫]
log-slave-updates
SlaveBSD# /usr/local/mysql/bin/safe_mysqld --user=mysql &
先檢測兩個Mysql數據庫中的repdatabase是否正常。
正常情況應該是Master和Slave 中的Mysql 都有相同的repdatabase 數據庫,並且裏面的數據都一樣。
然後我們測試replication 功能是否起用。
在Master中的repdatabas數據庫添加一筆數據:
Enter password:
Welcome to the MySQL monitor. Commands end with ; or /g.
Your MySQL connection id is 12 to server version: 3.23.53-log
Type 'help;' or '/h' for help. Type '/c' to clear the buffer.
mysql> use repdatabase;
Database changed
mysql> INSERT INTO `rep_table` ( `name` , `num` , `selectd ` ) VALUES ('test1', '4321', 'Y');
Query OK, 1 row affected (0.00 sec)
mysql>
Enter password:
Welcome to the MySQL monitor. Commands end with ; or /g.
Your MySQL connection id is 17 to server version: 3.23.56-log
Type 'help;' or '/h' for help. Type '/c' to clear the buffer.
mysql> select * from repdatabase.rep_table;
+--------+-----------+------------+
| name | num | selectd |
+--------+-----------+------------+
| aaa | 44444 | N |
| ddd | 111112222 | N |
| insert | 1234 | N |
| test | 12345 | N |
| test1 | 4321 | Y | 這一行就是Master插入的時候Slave 同步得回來的數據。
+--------+-----------+------------+
5 rows in set (0.01 sec)
mysql>
7、互爲replication
在Mysql 的文檔資料中也指出了,一臺Mysql機器同樣可以作爲Master也可以作爲Slave的,也可以互相replication數據。
8、應用
replication可以用在那方面呢?我的想法是,一臺Mysql生產機器在提供繁忙的SQL查詢,比如說是股市的查詢,那它僅僅是作爲查詢而已。那麼我們就可以通過兩臺機器,提供查詢的機器爲Slave,那麼數據錄入的機器是Master,通過雙網卡去進行,請看下圖:
這樣的好處是顯而易見,Slave作爲大量SQL查詢的服務器,繁忙、任務大!而且對着Internet,破壞可能性也大!因此,引入Mysql的replication我們可以方便、安全地管理數據庫!