Redis:优雅键值设计与BigKey处理指南
![](/theme/default/default/images/main/eye-open.png)
我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。
![](/theme/default/default/images/main/icon-jing.png)
Redis: Elegant Key Design and BigKey Handling Guide Summary
1. Elegant Key Structure
Redis keys should follow best practices, including a basic format of [business name]:[data name]:[data/data id], with a maximum length of 44 bytes, and no special characters for benefits like readability, conflict avoidance, easy management, and memory efficiency. For example, user information for a login service might be formatted as login:user:12345
. Keys shorter than 44 bytes use the more memory-efficient embstr
encoding.
2. Cautious Use of BigKeys
BigKeys can be identified by their size or member count, such as a 5 MB String key or a ZSET with 10,000 members. It is recommended to keep single key values under 10 KB and collections under 1000 elements, preferably not exceeding 5000. Redis introduced the MEMORY command in version 4.0 for size assessments, but its use is generally not recommended due to high CPU usage.
2.1. Dangers of BigKeys
BigKeys can cause network blockages, data skew, Redis blocking, and high CPU pressure, leading to performance degradation and imbalance in memory resources among data shards.
3. How to Discover BigKeys
To find BigKeys, use the redis-cli --bigkeys
option for a summary of keys, or programmatically scan all keys and assess sizes with commands like strlen
and hlen
. Using third-party tools like Redis-Rdb-Tools for RDB file analysis can provide a comprehensive memory usage analysis.
4. How to Delete BigKeys
Deleting BigKeys can be time-consuming and block the main thread of Redis. In versions before 3.0, it's suggested to remove elements of a collection one by one before deleting the entire BigKey. The DEL
command can remove keys but may impact performance due to its synchronous nature. Redis 4.0 introduced the unlink
command for asynchronous deletion.
想要了解更多内容?
![](/theme/default/default/images/main/icon-jing.png)
![](https://cdn.easycorp.cn/rongpm/upload/202312/f_39217d624bb2b42ce8f6322ebd7e573a.png)
![](https://cdn.easycorp.cn/rongpm/upload/202312/f_39217d624bb2b42ce8f6322ebd7e573a.png)