兩個mysql數據庫之間的主從同步

 

mysql主從複製實現數據庫同步html

master Mysql(主數據庫) : 192.168.211.128mysql

slave Mysql(從數據庫) : 192.168.211.130sql

# 測試使用數據庫
CREATE SCHEMA `user` DEFAULT CHARACTER SET utf8 ;
use user;
CREATE TABLE `user`.`user` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`)
);
INSERT INTO `user`.`user` (`id`, `name`) VALUES ('1', '張三');
INSERT INTO `user`.`user` (`id`, `name`) VALUES ('2', '李四');

一、主數據庫的操做

1.一、建立一個從數據庫複製主數據庫使用的帳號,擁有 replication slave 權限。

grant replication slave on *.* to 'repl'@'192.168.211.130' identified by 'repl';
flush privileges;

1.二、修改mysql配置文件 /etc/my.cnf 

# server標識
server-id=107

# 指定二進制日誌存儲地址,必須使用絕對地址
log-bin=/var/lib/mysql/mysql-bin

#須要備份的數據庫名,能夠重複設置
binlog-do-db=user

# 不須要備份的數據庫名,能夠重複設置
binlog-ignore-db=mysql

# 這個參數必定要加上,不然不會給更新記錄到二進制文件裏
log-slave-updates=1 

# 是跳過錯誤,繼續執行復制操做
slave-skip-errors=1

1.三、重啓mysqld服務,並獲取binlog日誌文件名和偏移量(position)<這寫參數會在從數據庫配置時用到>

systemctl restart mysqld.service
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 |      768 | user         | mysql            |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.01 sec)

二、從數據庫配置

2.一、修改從數據庫的配置文件 /etc/my.cnf 

# server標識
server-id=109

2.二、重啓服務

systemctl restart mysqld.service

2.三、配置從數據庫的複製帳號和密碼等參數

mysql> change master to
    -> master_host='192.168.211.128',
    -> master_user='repl',
    -> master_password='repl',
    -> master_log_file='mysql-bin.000001',
    -> master_log_pos=154;
Query OK, 0 rows affected, 2 warnings (0.05 sec)

2.四、查看配置結果

mysql> show slave status\G;
*************************** 1. row ***************************
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes

上面的查詢結果不少,可是隻要看上面連個參數是YES就能夠了,若是是NO,就從新配置 2.3 的步驟。數據庫

三、測試

能夠先到主數據庫上看一下master和slave線程的狀態,在mater上能夠看到slave的I/O線程建立的連接bash

mysql> show processlist\G;
*************************** 1. row ***************************
     Id: 2
   User: root
   Host: localhost
     db: NULL
Command: Query
   Time: 0
  State: starting
   Info: show processlist
*************************** 2. row ***************************
     Id: 3
   User: repl
   Host: 192.168.211.130:47617
     db: NULL
Command: Binlog Dump
   Time: 71
  State: Master has sent all binlog to slave; waiting for more updates
   Info: NULL
2 rows in set (0.00 sec)

先在主數據庫上插入數據,ide

INSERT INTO `user`.`user` (`id`, `name`) VALUES ('3', '王五');

再到從數據庫查詢測試

mysql> SELECT * FROM user.user;
+----+------+
| id | name |
+----+------+
|  1 | 張三 |
|  2 | 李四 |
|  3 | 王五 |
+----+------+
3 rows in set (0.01 sec)
相關文章
相關標籤/搜索