Programing

마스터와 슬레이브에 MySQL 복제의 경우 다른 데이터베이스가있는 경우 MySQL 데이터베이스를 다시 동기화하는 방법은 무엇입니까?

crosscheck 2020. 6. 27. 11:14
반응형

마스터와 슬레이브에 MySQL 복제의 경우 다른 데이터베이스가있는 경우 MySQL 데이터베이스를 다시 동기화하는 방법은 무엇입니까?


MySQL Server1MASTER 로 실행 중 입니다.
MySQL Server2SLAVE 로 실행 중 입니다.

이제 DB 복제가 MASTER 에서 SLAVE로 진행되고 있습니다.

Server2네트워크에서 제거하고 하루 후에 다시 연결하십시오. 이 후 master 및 slave의 데이터베이스에 불일치가 있습니다.

마스터에서 슬레이브로 가져온 DB를 복원 한 후에도 DB를 다시 동기화하는 방법으로도 문제가 해결되지 않습니까?


다음은 마스터-슬레이브 복제를 처음부터 다시 동기화하는 전체 단계별 절차입니다.

마스터에서 :

RESET MASTER;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;

그리고 마지막 명령 의 결과 값을 어딘가에 복사하십시오 .

클라이언트에 대한 연결을 닫지 않고 (읽기 잠금을 해제하므로) 명령을 실행하여 마스터 덤프를 가져 오십시오.

mysqldump -u root -p --all-databases > /a/path/mysqldump.sql

덤프가 아직 종료되지 않은 경우에도 잠금을 해제 할 수 있습니다. 이를 수행하려면 MySQL 클라이언트에서 다음 명령을 수행하십시오.

UNLOCK TABLES;

이제 scp 또는 선호하는 도구를 사용하여 덤프 파일을 슬레이브에 복사하십시오.

노예에서 :

mysql에 대한 연결을 열고 다음을 입력하십시오.

STOP SLAVE;

이 콘솔 명령으로 마스터의 데이터 덤프를로드하십시오.

mysql -uroot -p < mysqldump.sql

슬레이브 및 마스터 로그 동기화 :

RESET SLAVE;
CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=98;

위의 필드 값은 이전에 복사 한 값입니다.

마지막으로 다음을 입력하십시오.

START SLAVE;

입력 후 모든 것이 다시 작동하는지 확인하려면 다음을 수행하십시오.

SHOW SLAVE STATUS;

넌 봐야 해:

Slave_IO_Running: Yes
Slave_SQL_Running: Yes

그게 다야!


MySQL 사이트에서 이에 대한 문서가 구식이며 구식 건 (예 : interactive_timeout)으로 가득 차 있습니다. 마스터 내보내기의 일부로 읽기 잠금으로 FLUSH 테이블을 발행하는 것은 일반적으로 LVM 또는 zfs와 같은 스토리지 / 파일 시스템 스냅 샷과 조정될 때만 의미가 있습니다.

mysqldump를 사용하려는 경우 --master-data 옵션을 사용하여 인적 오류를 방지하고 가능한 빨리 마스터의 잠금을 해제해야합니다.

마스터가 192.168.100.50이고 슬레이브가 192.168.100.51이고 각 서버에 고유 한 서버 ID가 구성되어 있고 마스터에 이진 로깅이 있고 슬레이브가 my.cnf에서 읽기 전용 = 1 인 것으로 가정합니다.

덤프를 가져온 직후에 슬레이브가 복제를 시작할 수 있도록 준비하려면 CHANGE MASTER 명령을 실행하되 로그 파일 이름과 위치는 생략하십시오.

slaveserver> CHANGE MASTER TO MASTER_HOST='192.168.100.50', MASTER_USER='replica', MASTER_PASSWORD='asdmk3qwdq1';

슬레이브가 사용할 마스터에 GRANT를 발행하십시오.

masterserver> GRANT REPLICATION SLAVE ON *.* TO 'replica'@'192.168.100.51' IDENTIFIED BY 'asdmk3qwdq1';

압축을 사용하고 올바른 이진 로그 좌표를 자동으로 캡처하여 마스터를 화면에서 내 보냅니다.

mysqldump --master-data --all-databases --flush-privileges | gzip -1 > replication.sql.gz

replication.sql.gz 파일을 슬레이브에 복사 한 다음 zcat를 사용하여 슬레이브에서 실행중인 MySQL 인스턴스로 가져옵니다.

zcat replication.sql.gz | mysql

슬레이브에 명령을 발행하여 복제를 시작하십시오.

slaveserver> START SLAVE;

선택적으로 슬레이브에서 /root/.my.cnf를 업데이트하여 마스터와 동일한 루트 비밀번호를 저장하십시오.

5.1 이상인 경우 먼저 마스터의 binlog_format을 MIXED 또는 ROW로 설정하는 것이 가장 좋습니다. 기본 키가없는 테이블의 경우 행 기록 이벤트가 느려집니다. 슬레이브에서 잘못된 데이터를 생성 할 가능성이 적기 때문에 일반적으로 binlog_format = statement (마스터에서)의 대체 (및 기본) 구성보다 낫습니다.

복제를 필터링해야하지만 (아마도 안 됨) 슬레이브 옵션 인 replicate-wild-do-table = dbname. % 또는 replicate-wild-ignore-table = badDB. %로 수행하고 binlog_format = row 만 사용하십시오.

이 프로세스는 mysqldump 명령 동안 마스터에 대한 전역 잠금을 유지하지만 마스터에 영향을 미치지 않습니다.

mysqldump --master-data --all-databases --single-transaction (InnoDB 테이블 만 사용하기 때문에)을 사용하고 싶다면 MySQL Enterprise Backup 또는 xtrabackup이라는 오픈 소스 구현을 사용하는 것이 좋습니다. 퍼 코나)


슬레이브 (Server2)에 직접 쓰지 않는 한 유일한 문제는 Server2에 연결이 끊어진 이후 발생한 업데이트가 누락 된 것입니다. "START SLAVE;"로 슬레이브를 다시 시작하기 만하면됩니다. 모든 것을 속도로 되돌려 야합니다


Maatkit utilits가 도움이된다고 생각합니다. mk-table-sync를 사용할 수 있습니다. 이 링크를 참조하십시오 : http://www.maatkit.org/doc/mk-table-sync.html


다음은 일반적으로 mysql 슬레이브가 동기화되지 않을 때 수행하는 작업입니다. mk-table-sync를 보았지만 위험 섹션이 무섭다고 생각했습니다.

마스터에서 :

SHOW MASTER STATUS

출력 된 열 (File, Position)은 우리에게 조금 사용될 것입니다.

슬레이브에 :

STOP SLAVE

그런 다음 마스터 DB를 덤프하고 슬레이브 DB로 가져 오십시오.

그런 다음 다음을 실행하십시오.

CHANGE MASTER TO
  MASTER_LOG_FILE='[File]',
  MASTER_LOG_POS=[Position];
START SLAVE;

여기서 [파일] 및 [위치]는 "SHOW MASTER STATUS"에서 출력 된 값입니다.

도움이 되었기를 바랍니다!


다윗의 대답에 따라 ...

를 사용 SHOW SLAVE STATUS\G하면 사람이 읽을 수있는 결과를 얻을 수 있습니다.


나는이 질문에 매우 늦었지만이 문제가 발생하여 많은 검색을 한 후 Bryan Kennedy에서 다음 정보를 찾았습니다 .http : //plusbryan.com/mysql-replication-without-downtime

마스터에서 다음과 같은 백업을 수행하십시오.
mysqldump --skip-lock-tables --single-transaction --flush-logs --hex-blob --master-data = 2 -A> ~ / dump.sql

이제 파일의 헤드를 검사하고 MASTER_LOG_FILE 및 MASTER_LOG_POS의 값을 적어 두십시오. 나중에 필요할 것입니다 : head dump.sql -n80 | grep "MASTER_LOG"

"dump.sql"파일을 슬레이브로 복사하고 복원하십시오 : mysql -u mysql-user -p <~ / dump.sql

슬레이브 mysql에 연결하고 CHANGE MASTER TO MASTER_HOST = 'master-server-ip', MASTER_USER = 'replication-user', MASTER_PASSWORD = 'slave-server-password', MASTER_LOG_FILE = '상기 값', MASTER_LOG_POS = 위의 값; 슬레이브 시작;

슬레이브의 진행 상황을 확인하려면 : SHOW SLAVE STATUS;

모두 정상이면 Last_Error가 비어 있고 Slave_IO_State는 "마스터가 이벤트를 기다리는 중"을보고합니다. 뒤가 얼마나 멀리 있는지 나타내는 Seconds_Behind_Master를 찾으십시오. YMMV. :)


다음은 희망적으로 다른 사람들을 도울 완전한 답변입니다 ...


마스터와 슬레이브를 사용하여 mysql 복제를 설정하고 싶습니다. 알고있는 유일한 것은 로그 파일을 사용하여 동기화하는 것입니다. 슬레이브가 오프라인 상태가되어 동기화되지 않으면 이론적으로는 다시 연결하면됩니다. 사용자 malonso가 언급했듯이 로그 파일을 마스터에서 계속 중단하고 로그 파일을 읽습니다.

다음은 마스터 및 슬레이브를 구성한 후의 테스트 결과입니다. http://dev.mysql.com/doc/refman/5.0/en/replication-howto.html ...

Provided you use the recommended master/slave configuration and don't write to the slave, he and I where right (as far as mysql-server 5.x is concerned). I didn't even need to use "START SLAVE;", it just caught up to its master. But there is a default 88000 something retries every 60 second so I guess if you exhaust that you might have to start or restart the slave. Anyways, for those like me who wanted to know if having a slave going offline and back up again requires manual intervention.. no, it doesn't.

Maybe the original poster had corruption in the log-file(s)? But most probably not just a server going off-line for a day.


pulled from /usr/share/doc/mysql-server-5.1/README.Debian.gz which probably makes sense to non debian servers as well:

* FURTHER NOTES ON REPLICATION
===============================
If the MySQL server is acting as a replication slave, you should not
set --tmpdir to point to a directory on a memory-based filesystem or to
a directory that is cleared when the server host restarts. A replication
slave needs some of its temporary files to survive a machine restart so
that it can replicate temporary tables or LOAD DATA INFILE operations. If
files in the temporary file directory are lost when the server restarts,
replication fails.

you can use something sql like: show variables like 'tmpdir'; to find out.


Adding to the popular answer to include this error:

"ERROR 1200 (HY000): The server is not configured as slave; fix in config file or with CHANGE MASTER TO",

Replication from slave in one shot:

In one terminal window:

mysql -h <Master_IP_Address> -uroot -p

After connecting,

RESET MASTER;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;

The status appears as below: Note that position number varies!

+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      98  | your_DB      |                  |
+------------------+----------+--------------+------------------+

Export the dump similar to how he described "using another terminal"!

Exit and connect to your own DB(which is the slave):

mysql -u root -p

The type the below commands:

STOP SLAVE;

Import the Dump as mentioned (in another terminal, of course!) and type the below commands:

RESET SLAVE;
CHANGE MASTER TO 
  MASTER_HOST = 'Master_IP_Address', 
  MASTER_USER = 'your_Master_user', // usually the "root" user
  MASTER_PASSWORD = 'Your_MasterDB_Password', 
  MASTER_PORT = 3306, 
  MASTER_LOG_FILE = 'mysql-bin.000001', 
  MASTER_LOG_POS = 98; // In this case

Once logged, set the server_id parameter (usually, for new / non-replicated DBs, this is not set by default),

set global server_id=4000;

Now, start the slave.

START SLAVE;
SHOW SLAVE STATUS\G;

The output should be the same as he described.

  Slave_IO_Running: Yes
  Slave_SQL_Running: Yes

Note: Once replicated, the master and slave share the same password!


sometimes you just need to give the slave a kick too

try

stop slave;    
reset slave;    
start slave;    
show slave status;

quite often, slaves, they just get stuck guys :)


I created a GitHub repo with an script to solve this problem quickly. Just change a couple variables and run it (First, the script creates a backup of your database).

I hope this help you (and others people too).

How to Reset (Re-Sync) MySQL Master-Slave Replication


We are using master-master replication technique of MySQL and if one MySQL server say 1 is removed from the network it reconnects itself after the connection are restored and all the records that were committed in the in the server 2 which was in the network are transferred to the server 1 which has lost the connection after restoration. Slave thread in the MySQL retries to connect to its master after every 60 sec by default. This property can be changed as MySQL ha a flag "master_connect_retry=5" where 5 is in sec. This means that we want a retry after every 5 sec.

But you need to make sure that the server which lost the connection show not make any commit in the database as you get duplicate Key error Error code: 1062


Rebuilding the slave using LVM

Here is the method we use to rebuild MySQL slaves using Linux LVM. This guarantees a consistent snapshot while requiring very minimal downtime on your master.

Set innodb max dirty pages percent to zero on the master MySQL server. This will force MySQL to write all the pages to the disk which will significantly speed up the restart.

set global innodb_max_dirty_pages_pct = 0;

To monitor the number of dirty pages run the command

mysqladmin ext -i10 | grep dirty

Once the number stop decreasing you have reach the point to continue. Next reset the master to clear the old bin logs / relay logs:

RESET MASTER;

Execute lvdisplay to get LV Path

lvdisplay

Output will look like this

--- Logical volume ---
LV Path                /dev/vg_mysql/lv_data
LV Name                lv_data
VG Name                vg_mysql

Shutdown the master database with command

service mysql stop

Next take a snaphot, mysql_snapshot will be the new logical volume name. If binlogs are place on the OS drive those need to be snapshot as well.

lvcreate --size 10G --snapshot --name mysql_snapshot /dev/vg_mysql/lv_data

Start master again with command

service mysql start

Restore dirty pages setting to the default

set global innodb_max_dirty_pages_pct = 75;

Run lvdisplay again to make sure the snapshot is there and visible

lvdisplay

Output:

--- Logical volume ---
LV Path                /dev/vg_mysql/mysql_snapshot
LV Name                mysql_snapshot
VG Name                vg_mysql

Mount the snapshot

mkdir /mnt/mysql_snapshot
mount /dev/vg_mysql/mysql_snapshot /mnt/mysql_snapshot

If you have an existing MySQL slave running you need to stop it

service mysql stop

Next you need to clear MySQL data folder

cd /var/lib/mysql
rm -fr *

Back to master. Now rsync the snapshot to the MySQL slave

rsync --progress -harz /mnt/mysql_snapshot/ targethostname:/var/lib/mysql/

Once rsync has completed you may unmount and remove the snapshot

umount /mnt/mysql_snapshot
lvremove -f /dev/vg_mysql/mysql_snapshot

Create replication user on the master if the old replication user doesn't exist or password is unknown

GRANT REPLICATION SLAVE on *.* to 'replication'@'[SLAVE IP]' identified by 'YourPass';

Verify that /var/lib/mysql data files are owned by the mysql user, if so you can omit the following command:

chown -R mysql:mysql /var/lib/mysql

Next record the binlog position

ls -laF | grep mysql-bin

You will see something like

..
-rw-rw----     1 mysql mysql  1073750329 Aug 28 03:33 mysql-bin.000017
-rw-rw----     1 mysql mysql  1073741932 Aug 28 08:32 mysql-bin.000018
-rw-rw----     1 mysql mysql   963333441 Aug 28 15:37 mysql-bin.000019
-rw-rw----     1 mysql mysql    65657162 Aug 28 16:44 mysql-bin.000020

Here the master log file is the highest file number in sequence and bin log position is the file size. Record these values:

master_log_file=mysql-bin.000020
master_log_post=65657162

Next start the slave MySQL

service mysql start

Execute change master command on the slave by executing the following:

CHANGE MASTER TO 
master_host="10.0.0.12", 
master_user="replication", 
master_password="YourPass", 
master_log_file="mysql-bin.000020", 
master_log_pos=65657162; 

Finally start the slave

SLAVE START;

Check slave status:

SHOW SLAVE STATUS;

Make sure Slave IO is running and there are no connection errors. Good luck!

BR, Juha Vehnia

I recently wrote this on my blog which is found here... There are few more details there but the story is the same.

http://www.juhavehnia.com/2015/05/rebuilding-mysql-slave-using-linux-lvm.html

참고URL : https://stackoverflow.com/questions/2366018/how-to-re-sync-the-mysql-db-if-master-and-slave-have-different-database-incase-o

반응형