search

Redis主备同步

Jun 07, 2016 pm 04:41 PM
redischangeSynchronizestate

slave状态变迁 #define REDIS_REPL_NONE 0 /* No active replication */#define REDIS_REPL_CONNECT 1 /* Must connect to master */#define REDIS_REPL_CONNECTING 2 /* Connecting to master */#define REDIS_REPL_RECEIVE_PONG 3 /* Wait for PING reply

slave状态变迁

<code>#define REDIS_REPL_NONE 0 /* No active replication */
#define REDIS_REPL_CONNECT 1 /* Must connect to master */
#define REDIS_REPL_CONNECTING 2 /* Connecting to master */
#define REDIS_REPL_RECEIVE_PONG 3 /* Wait for PING reply */
#define REDIS_REPL_TRANSFER 4 /* Receiving .rdb from master */
#define REDIS_REPL_CONNECTED 5 /* Connected to master */
</code>

server.repl_state储存slave当前的复制状态

* redis启动时初始化为REDIS_REPL_NONE

* 当接受到slaveof命令后,该redis转换为slave,同时状态变为REDIS_REPL_CONNECT

周期性执行的replicationCron会检查slave当前的状态,来执行不同的操作

  • 如果slave处于REDIS_REPL_CONNECT,调用connectWithMaster建立到master的连接,状态转换为REDIS_REPL_CONNECTING
  • 连接建立后,向master发送PING,状态转换为REDIS_REPL_RECEIVE_PONG
  • 接受到PONG后,如果master配置了需要认证,则slave发送AUTH消息,AUTH通过后;slave发送REPLCONF listening-port消息到master告知自身监听的端口;最后向master发送SYNC命令来请求同步rdb文件,同时状态转换为REDIS_REPL_TRANSFER。
  • 当master向slave发送rdb后,slave就开始读取rdb文件(master发送rdb前会先告知rdb文件的总长度),slave接受完rdb文件后,会emptyDb清空数据库,然后调用rdbLoad加载从master接受到的rdb文件,加载完成后状态变为REDIS_REPL_CONNECTED,接下来slave会继续接受从master同步过来的新操作,以保证主备的一致性。

master状态变迁

<code>#define REDIS_REPL_WAIT_BGSAVE_START 6 /* We need to produce a new RDB file. */
#define REDIS_REPL_WAIT_BGSAVE_END 7 /* Waiting RDB file creation to finish. */
#define REDIS_REPL_SEND_BULK 8 /* Sending RDB file to slave. */
#define REDIS_REPL_ONLINE 9 /* RDB file transmitted, sending just updates. */
</code>

server.slaves里维护所有的slave列表,slave.replstate里记录着每个slave当前的同步状态(从master的视角看)。

  • 当master接受到slave发来的sync/psync命令时,将该slave的状态转换为REDIS_REPL_WAIT_BGSAVE_START
  • master为该slave后台启动rdbSaveBackground,并将该slave的状态转换为REDIS_REPL_WAIT_BGSAVE_END (如果master己收到sync时,master正在为某个slave转储rdb文件,则新的slave可以直接进入REDIS_REPL_WAIT_BGSAVE_END状态)
  • 当rdbSaveBackground完成后,slave的状态转换为REDIS_REPL_SEND_BULK,master开始将rdb文件发送给slave,发送前会先发送rdb文件的长度信息。
  • 当rdb文件发送完成后,slave的状态转换为REDIS_REPL_ONLINE。

master在为slave启动rdbSaveBackground后,master上的更新会累积到slave的连接缓冲区,等到slave接受完rdb文件之后,将缓冲区里累积的更新同步到slave上

主备同步时序

  1. 管理员向server发送slaveof master-ip master-port,将该server变为master的slave
  2. slave建立到master的网络连接
  3. slave向master发送PING检测网络状态,master回复+PONG
  4. slave向master发送AUTH进行认证(可选),master恢复+OK
  5. slave向master发送REPLCONF listening-port,master恢复+OK
  6. slave向master发送sync/psync,master开始后台转储rdb文件
  7. master转储rdb完成后,向slave发送rdb文件,slave接受rdb文件并清空数据库,load从master接受到的rdb文件
  8. master将rdb转储及传输期间累积的更新操作同步到slave
  9. master与slave数据到达一致,接下来master接受到的所有更新操作都会同步到slave

主备同步状态维护

master周期性的ping slave(默认10s),当ping不通slave超过60s(默认)后,就会认为slave挂掉了,便会断开与该slave的连接;同理,slave如果超过一定时间没有接受到master的PING,会认为master挂掉了,便会断开与master的连接。

当master、slave连接断开后,slave需要重新向master请求同步rdb文件;2.8版本里redis一定程度支持增量同步,master将同步数据同步给slave时,会同时存储到一个环形缓冲区(默认1M大小),这个缓冲区永远存储最新的同步数据;另外master、slave都会记录当前同步的offset。

当slave与master断开后,slave会先尝试进行PSYNC增量同步,如果连接断开期间,master没有重启过,并且slave的offset在master的环形缓冲区内,则可直接进行增量同步,比如:

假设环形缓冲区的长度为1000, master的同步offset为10000,此时缓冲区里记录的是9001-10000的同步数据,slave同步到9500时,与master断开了连接;slave重新建立与master连接后,会带上offset 9500,请求增量同步,master发现该slave的offset在9001-10000之间,可以进行增量同步,将9501-10000的同步数据发送给slave,以达到主备一致的状态。

The post Redis主备同步 appeared first on Yun Notes.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment