前言

Github:https://github.com/HealerJean

博客:http://blog.healerjean.com

1、Key的设计规范

高可读性、区分性和尽量简洁

1、按业务功能命名 key 前缀,防止 key 冲突覆盖,同时方便运维管理

2、Key 的长度小于 30 个字符,Key 内容本身分占用1到多份内存容量

  **2.1、Key 名字本身是 String 对象,最大长度 512MB **

  2.2、建议Key使用”:”字符进行分层

3、Redis 缓存场景,建议Key都设置TTL值,保证不使用的Key能被及时清理或淘汰,使内存复用

2、程序架构规范

1、Cluster模式中,热点Key和大容量Key尽量设计”打散”;避免集群不均,导致某个分片QPS“过载“和容量过大

2、避免使用时间复杂度为O(N)的访问模式或命令,对元素比较多的集群key使用时间复杂度为O(N)命令,往往会造成一些问题,如下。

  2.1、redis是单线程的,如果命令耗时过长,命令独占server,其间不能响应其他命令,导致服务超时。如果执行时间比较长,甚于导致判断节点为下线状态,触发集群故障转移。

  2.2、时间复杂度为O(N)的常见命令:

命令 时间复杂度描述 替换或改进
mset O(N) where N is the number of keys to set. 一次mset/mgetKey个数尽量<10000个
hgetall O(N) where N is the size of the hash. 对于字段较多的hash(10w个),使用hscan命令替换
hkeys O(N) where N is the size of the hash. 对于字段较多的hash(10w个),使用hscan命令替换
lrange 0,-1 O(S+N) where S is the distance of start offset from HEAD for small lists, from nearest end (HEAD or TAIL) for large lists; and N is the number of elements in the specified range. 尽量切割为分段获取
smembers O(N) where N is the set cardinality. 对于元素较多的set(10万),可用scan代替。
sunion O(N) where N is the total number of elements in all given sets. 减少set的元素和同时操作的set key个数
sinterstore O(N*M) worst case where N is the cardinality of the smallest set and M is the number of sets. 减少set的元素和同时操作的set key个数
zrem O(M*log(N)) with N being the number of elements in the sorted set and M the number of elements to be removed. 减少一次删除的元素个数
zunionstore O(N)+O(M log(M)) with N being the sum of the sizes of the input sorted sets, and M being the number of elements in the resulting sorted set. 减少操作的有序集合个数和集合本身的元数个数
keys O(N) with N being the number of keys in the database 避免使用keys命令,使用scan进行替换

3、生产环境严禁使用的危险命令

1、keys * :导致Redis实例堵死,甚于触发故障切换,导致整个集群出现大面积的故障

2、flushall: 导致Redis堵死,同时丢失所有数据

3、flushdb: 丢失当前database的所有数据,出现堵死现象

4、save: 导致Redis堵死

5、bgsave: 导致Redis卡顿,FORK引起COW内存消耗,有导致大面积OOM的风险

6、config set:严禁开发同学修改生产配置,错误配置会导致数据丢失和OOM的风险

7、shutdown: 导致Redis关闭、数据丢失和故障转移

8、debug : 导致Redis Crash、堵死和集群故障转移等

9、慎用时间复杂度为O(N)的命令方法,

ContactAuthor