Dispersing Keys in a Cluster Instance
A Redis cluster distributes data across multiple nodes by hashing keys into 16,384 slots. Each key is mapped to a specific hash slot using a hash function.
However, keys with similar patterns may be mapped to the same hash slot, leading to uneven distribution across the cluster. To avoid this, do as follows to disperse keys.
Dispersing Keys in a Cluster Instance
- By hash tags
Hash tags can effectively disperse keys but the keys' logic must be consistent.
Redis controls key distribution using hash tags. A hash tag is contained in a brace pair {} and a hash value is calculated only by it.
Example:
Keys:
user:1 user:2 user:3
These keys may be hashed to one slot. To prevent this, use hash tags:
user:{1} user:{2} user:{3}
Redis calculates hash values based on {1}, {2}, and {3}, and distributes keys to different slots.
- By random key names
Random key names effectively balance loads but may increase key complexity.
When hash tags are not available, add random strings or UUIDs to key names to disperse keys.
Example:
import uuid def generate_key(base_key): random_part = str(uuid.uuid4())[:8] # Randomly generates an 8-bit string. return f"{base_key}:{random_part}" # Use key = generate_key("user") print(key) # user:123e4567
Keys can be dispersed based on a random part contained in each key.
- By varying key prefixes
If key naming is fixed, add different prefixes to disperse keys.
Example:
user:1 -> user1:1 user:2 -> user2:2 user:3 -> user3:3
Different key prefixes result in distinct hash values.
Querying Slot Distribution
Use the CLUSTER INFO and CLUSTER KEYSLOT commands.
Example:
redis-cli -c -h <node_ip> -p <node_port> CLUSTER INFO redis-cli -c -h <node_ip> -p <node_port> CLUSTER KEYSLOT <key>
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot