What is a Redis cluster
Redis cluster is a distributed database solution provided by Redis. The cluster shares data through sharding and provides replication and failover functions. A cluster is usually composed of multiple nodes. At the beginning, each node is independent of each other and in a cluster that only contains itself. To build a truly working cluster, we must connect the independent nodes together to form a cluster containing multiple nodes.
A node can be “pulled” into the cluster by shaking hands as above. Run the CLUSTER MEET IP :port command
You can view NODES in the current CLUSTER.
The Redis server determines whether to enable cluster mode based on whether cluster-Enabled is set to Yes.
Cluster data structure
ClusterNode stores the current status of a node. Each node has a clusterNode
Struct clusterNode {// Create node time mstime_t ctime; // Node name char name[REDIS_CLUSTER_NAMELEN]; // Node flags, primary node, secondary node, and current state int flags; // The current configuration epoch of the node for failover unit64_t configEpoch; // Node IP char IP [REDIS_IP_STR_LEN]; // Node port int port; ClusterLink *link; I unsigned char slots[2048]; // The number of bits is 16384. / /... }Copy the code
Each node keeps a clusterState structure, which records the current state of the cluster from the perspective of the current node.
Struct clusterState {// clusterNode *myself; // The current configuration era, used to failover the uint64_t currentEpoch; // Cluster status, online or offline int state; // The number of nodes in the cluster that handle at least one slot int size; // List of nodes in the cluster dict *nodes; }Copy the code
Using the first three nodes as an example, here is a clusterState example
From this figure, we can see the process of handshake, which is the process of two nodes building clusterNode and clusterState with each other. After A shakes hands with B, A notifies other nodes in the cluster and shakes hands with B one by one.
Slots assigned
Redis cluster stores key-value pairs of database by sharding: the whole database of the cluster is divided into 16384 slots, each key in the database belongs to one of the slots, and each node in the cluster can handle several slots.
When a node is being processed in each slot of the database, the cluster is online; otherwise, the cluster is offline.