search
HomeDatabaseRedisLet's talk about master-slave synchronization and sentinel mode in Redis

Let's talk about master-slave synchronization and sentinel mode in Redis

Feb 08, 2022 am 09:55 AM
redisMaster-slave synchronization

This article will give you an in-depth understanding of master-slave synchronization and sentinel mode in Redis, and introduce how to turn on and off master-slave synchronization, and build and start Sentinel. I hope it will be helpful to everyone!

Let's talk about master-slave synchronization and sentinel mode in Redis

Master-slave synchronization

Master-slave synchronization (master-slave replication) is the cornerstone of Redis high availability service and also The most basic in multi-machine operation. [Related recommendations: Redis Video Tutorial]

We call the node that mainly stores data the master node (master), and call other replica nodes that copy the master node data It is called a slave node (slave), as shown in the following figure:

Lets talk about master-slave synchronization and sentinel mode in Redis

In Redisa master node can have Multiple slave nodes,A slave node can also be the master node of other servers, as shown in the following figure:

Lets talk about master-slave synchronization and sentinel mode in Redis

Advantages of master-slave synchronization

Master-slave synchronization has the following three advantages:

  • Performance aspect: With master-slave synchronization, you can assign the query task to the slave server , use the master server to perform write operations , which greatly improves the efficiency of program operation. All pressure is distributed to each server;
  • High availability: With master-slave synchronization, when the main server node goes down, it can be quickly Promote the slave node to the master node, which saves valuable time for Redis server downtime recovery;
  • Prevent data loss: When the master server After the disk is damaged, other slave servers still retain relevant data, so that all data will not be lost.

Enable master-slave synchronization

Set up the slave server during operation

InRedis During the running process, we can use the replicaof host port command to set ourselves as the slave server of the target IP.

If the master service has set a password, you need to enter the password of the master server on the slave server, use the config set masterauth master service password command method

After executionreplicaof After the command, the slave server's data will be cleared, and the master service will synchronize its data copy to the slave server.

Set the slave server at startup

You can use the command redis-server --port 6380 --replicaof 127.0.0.1 6379 to set yourself to The slave server of the target server.

Data synchronization

Complete data synchronization

When there is a new slave server connection, In order to ensure the consistency of multiple databases, the main server will execute the bgsave command once to generate a RDB file, and then use Socket method is sent to the slave server. After receiving the RDB file from the server, it loads all the data into its own program, completing a full data synchronization.

Partial data synchronization

Before Redis 2.8, every time the slave server went offline and came back online, the master server would perform a complete data synchronization , and if this happens when the offline time is relatively short, it would be very clumsy and uneconomical to synchronize all the data while only a small amount of data is out of sync. This function has been optimized in Redis 2.8 .

The optimization method of Redis 2.8 is that when the slave service goes offline, the master server will store the write commands after the offline in a queue of a specific size. The queue can guarantee first-in-first-out According to the execution sequence, when the slave server is rewritten and restored online, the master service will determine whether the commands during the offline period are still in the queue. If so, it will directly send the data in the queue to the slave server, thus avoiding Complete synchronization is a waste of resources.

The default queue size for storing offline commands is 1MB. Users can modify the queue size configuration item repl-backlog-size.

Diskless data synchronization

During the first master-slave connection, a RDB file will be generated first, and then RDB files are sent to the slave server. If the master server is a non-SSD, the system's I/O operation is very high.

Redis 2.8.18 Added a new diskless copy function. The diskless copy function will not create RDB files locally, but will spawn a child process, and then the child process will be created. The process directly writes the RDB file to the slave server through Socket, so that the master server can complete the transaction without creating the RDB file. Data synchronization from server.

To use the copy-free function, just set the value of the configuration item repl-diskless-sync to yes. Its default configuration value is no.

Query the role of the server

Use the role command to query the master-slave role information of the current server.

Close master-slave synchronization

You can use the replicaof no one command to stop replication from the slave server.

After executing the replicaof no one command, I changed from the server to the master server.

Conversion of server type will not affect the data, and the data of this server will be retained.

Notes

Data consistency issues

When the slave server has completed and the master service After the data is synchronized, the new command will be sent to the slave server in an asynchronous manner. During this process, the master-slave synchronization will have short-term data inconsistency. If the master server goes down before this asynchronous synchronization occurs, the data will be Inconsistent.

Slave server read-only

By default, the master server in replication mode can perform both write operations and read operations, while the slave server can only Perform a read operation.

You can execute the config set replica-read-only no command on the slave server to enable the slave server to enable write mode, but you need to pay attention to the following points:

  • Data written on the slave server will not be synchronized to the master server;
  • When the key values ​​are the same, the data on the master server can overwrite the slave server;
  • When performing complete data synchronization, the slave server Server data will be cleared.

Changes in replication commands

Redis 5.0 The replication command used before was slaveof, in Redis 5.0 The replication command was changed to replicaof after #Redis 5.0. In higher versions (Redis 5 ) we should try to use replicaof because slaveof

Commands may be discarded at any time.

Sentinel Mode

Master-slave replication mode is the basis of Redis multi-machine operation, but this mode itself has a fatal problem. When the master After a node crashes, manual intervention is required to restore normal use of Redis

.

We need an automatic tool - Redis Sentinel (sentinel mode) to turn the manual process into automatic, so that Redis has automatic disaster recovery ( failover

) ability.

The sentinel is equivalent to performing a monitoring task on the master and slave servers. Once it is discovered that the master server is down, the corresponding rules will be quickly activated to upgrade a slave server to the master server without manual intervention, making it more stable and faster

.

Redis Sentinel

The minimum allocation unit is one master and one slave.

Lets talk about master-slave synchronization and sentinel mode in Redis

Redis Sentinel build

Use the command./src/redis- sentinel sentinel.conf to start Sentinel. When starting it, you must set up a sentinel.conf

file. This configuration file must contain the listening master node information:

sentinel monitor master-name ip port quorum

Among them:
  • master-name
  • means giving a name to the monitored master node;
  • #ip
  • means the master node IP;
  • port
  • represents the port of the master node;
  • quorum represents the number of Sentinel that confirmed that the master node is offline , if quorum is set to 1, it means that as long as one Sentinel
  • determines that it is offline, you can confirm that it is really offline.

If the master node server Redis has a password, sentinel.conf

must contain the following:

sentinel monitor mymaster 127.0.0.1 6379 1
sentinel auth-pass mymaster pwd654321
Start the Sentinel cluster

In the production environment, we will not only start oneSentinel, because if we start oneSentinel, if it unfortunately crashes , we cannot provide automatic disaster recovery services, which is not in line with our high-availability purpose, so we will start multiple Sentinel on different physical machines to form a Sentinel cluster to ensure Redis

High availability of services. ###

StartingSentinel The method of starting a cluster is very simple. It is the same as the method of starting a single server above. We only need to monitor multiple Sentinel to one main server node, so multipleSentinel will automatically discover each other and form a Sentinel cluster.

Lets talk about master-slave synchronization and sentinel mode in Redis

Generally, the number of Sentinel clusters is an odd number greater than 1. The parameters of quorum are set to half plus 1. For example, 5 is set to 3, and 7 is set to 4.

Two concepts: subjective offline and objective offline.

When one Sentinel in the Sentinel cluster thinks that the main server has been offline, it will mark the main server as subjectively offline (Subjectively Down, SDOWN), and then ask other Sentinel in the cluster whether they also think that the server is offline. When the Sentinel# agrees that the main server is offline, ## When the number reaches the number specified by the quorum parameter, Sentinel will mark the corresponding main server as objectively offline (Objectively down, ODOWN), Then start failing over it.

Main service election rules

New master node election priority setting

The replica-priority option in redis.conf is used to set the priority of running for a new master node. Its default value is 100, and its maximum value is also 100. The smaller this value, the lower its weight. The higher.

New master node election rules

The election of the new master node will exclude slave nodes that do not meet the conditions, and then the remaining slave nodes will be selected according to priority.

Slave nodes with the following conditions will be excluded:

  • Exclude all suspected offline slave servers that have been offline and have not responded to heartbeat detection for a long time;

  • Exclude all slave servers that have not communicated with the master server for a long time and have outdated data status;

  • Exclude all slave servers (

    replica-priority ) is 0 server.

Eligible slave node election order:

  • The slave node with the highest priority will be the new master node;

  • If the priorities are equal, the replication offset will be determined, and the slave node with the largest offset will win;

  • If the above two conditions are the same, select

    Redis Randomly generates the one with the smallest ID during runtime as the new master server.

The old master node comes back online

If the previous old master node comes back online, it will run in the master-slave server mode as a slave node.

Sentinel working principle

First of all, each

Sentinel will send a message to a known person at a frequency of 1 time per second. The master server, slave server and other Sentinel instances send a PING command.

If the time for the last valid reply to the

PING command exceeds the value configured by down-after-milliseconds (default 30s), then this instance will be Sentinel is marked as subjective offline.

If a main server is marked as subjective offline, then all

Sentinel nodes that are monitoring the main server must confirm that the main server has indeed entered subjective offline at a frequency of 1 time per second. line status.

If a sufficient number (

quorum configuration value) of Sentinel agree with this judgment within the specified time range, then the master server is marked as objectively offline . At this time, all Sentinel will automatically select a new master node according to rule negotiation.

NOTE: A valid

PING reply can be: PONG, -LOADING or -MASTERDOWN. If the return value is not the above three replies, or there is no reply to the PING command within the specified time, then Sentinel considers the reply returned by the server to be invalid (non-valid) .

Sentinel command operation

Sentinel can monitor multiple master nodes instead of only one server. If you want to monitor multiple master nodes, you only need to set multiple sentinel monitor master-name ip port quorum in the configuration file. We use master-name to distinguish different master nodes. .

Query the information of all monitored master servers

sentinel masters

Query the information of a certain master node

sentinel master master-name

View the IP and port of a master node

sentinel get-master-addr-by-name master-name

Query slave node information

sentinel replicas mymaster orsentinel slaves master-name

Query other Sentinel information in the Sentinel cluster

sentinel sentinels master-name

检查可用 Sentinel 的数量

sentinel ckquorum master-name

强制故障转移

sentinel failover master-name

在线修改配置信息

Redis 2.8.4 之前如果需要修改 Sentinel 的配置文件,需要重启 Sentinel

Redis 2.8.4 之后,我们可以在线修改配置文件了。

增加监视主节点

sentinel monitor mymaster IP Port Quorum 命令。

移除主节点的监视

使用 sentinel remove master-name 命令。

修改 quorum 参数

使用 sentinel set master-name quorum n 命令。

quorum 参数用来表示确认主节点下线的 Sentinel 数量,如果 quorum 设置为 1 表示只要有一台 Sentinel 确认主观下线后,这个主节点就客观(真正地)下线了。

以上所有对配置文件的修改,都会自动被刷新到物理配置文件 sentinel.conf

代码实战

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
import utils.Config;

import java.util.HashSet;
import java.util.Set;

public class SentinelExample {
    // master name
    private static String _MASTER_NAME = "mymaster";

    public static void main(String[] args) {
        // Sentinel 配置信息
        Set<String> set = new HashSet<>();
        // 连接信息 ip:port
        set.add("127.0.0.1:26379");
        // 创建 Sentinel 连接池
        JedisSentinelPool jedisSentinel = new JedisSentinelPool(_MASTER_NAME,
                set, Config.REDIS_AUTH);
        // 获取 Redis 客户端
        Jedis jedis = jedisSentinel.getResource();
        // 设置元素
        String setRes = jedis.set("key", "Hello, redis.");
        System.out.println(setRes);
        // 获取元素
        System.out.println(jedis.get("key"));
    }
}

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Let's talk about master-slave synchronization and sentinel mode in Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Redis: Classifying Its Database ApproachRedis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AM

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Why Use Redis? Benefits and AdvantagesWhy Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AM

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Understanding NoSQL: Key Features of RedisUnderstanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AM

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

Redis: Identifying Its Primary FunctionRedis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AM

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis: A Guide to Popular Data StructuresRedis: A Guide to Popular Data StructuresApr 11, 2025 am 12:04 AM

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.

How to implement redis counterHow to implement redis counterApr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to use the redis command lineHow to use the redis command lineApr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to build the redis cluster modeHow to build the redis cluster modeApr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.