前者主要表示Redis键的占用内存大小;后者表示Redis集合数据类型(set/hash/list/sorted set)键,所含有的元素个数。以下两个示例:
1个大小200MB的String键(String Object最大512MB);内存空间角度占用较大
1个包含100000000(1kw)个字段的Hash键,对应访问模式(如hgetall)时间复杂度高
因为内存空间复杂性处理耗时都非常小,测试 del 200MB String键耗时约1毫秒,
而删除一个含有1kw个字段的Hash键,却会阻塞Redis进程数十秒。所以本文只从时间复杂度分析大的集合类键。删除这种大键的风险,以及怎么优雅地删除。
在Redis集群中,应用程序尽量避免使用大键;直接影响容易导致集群的容量和请求出现”倾斜问题“,具体分析见文章: redis-cluster-imbalance 。但在实际生产过程中,总会有业务使用不合理,出现这类大键;当DBA发现后推进业务优化改造,然后删除这个大键;如果直接删除它,DEL命令可能阻塞Redis进程数十秒,对应用程序和Redis集群可用性造成严重的影响。
直接删除大Key的风险DEL命令 在删除单个集合类型的Key时,命令的时间复杂度是O(M),其中M是集合类型Key包含的元素个数。
DEL key
Time complexity: O(N) where N is the number of keys that will be removed. When a key to remove holds a value other than a string, the individual complexity for this key is O(M) where M is the number of elements in the list, set, sorted set or hash. Removing a single key that holds a string value is O(1).
生产环境中遇到过多次因业务删除大Key,导致Redis阻塞,出现故障切换和应用程序雪崩的故障。
测试删除集合类型大Key耗时,一般每秒可清理100w~数百w个元素; 如果数千w个元素的大Key时,会导致Redis阻塞上10秒
可能导致集群判断Redis已经故障,出现故障切换;或应用程序出现雪崩的情况。
说明:Redis是单线程处理。
单个耗时过大命令,导致阻塞其他命令,容易引起应用程序雪崩或Redis集群发生故障切换。
所以避免在生产环境中使用耗时过大命令。
Redis删除大的集合键的耗时, 测试估算,可参考;和硬件环境、Redis版本和负载等因素有关
Key类型 Item数量 耗时 Hash ~100万 ~1000ms List ~100万 ~1000ms Set ~100万 ~1000ms Sorted Set ~100万 ~1000ms当我们发现集群中有大key时,要删除时,如何优雅地删除大Key?
如何优雅地删除各类大Key从Redis2.8版本开始支持 SCAN 命令,通过m次时间复杂度为O(1)的方式,遍历包含n个元素的大key.
这样避免单个O(n)的大命令,导致Redis阻塞。 这里删除大key操作的思想也是如此。
Delete Large Hash Key通过 hscan命令 ,每次获取500个字段,再用 hdel命令 ,每次删除1个字段。
python代码:
defdel_large_hash(): r = redis.StrictRedis(host='redis-host1', port=6379) large_hash_key ="xxx"#要删除的大hash键名 cursor = '0' whilecursor !=0: cursor, data = r.hscan(large_hash_key, cursor=cursor, count=500) foritemindata.items(): r.hdel(large_hash_key, item[0]) Delete Large Set Key删除大set键,使用 sscan命令 ,每次扫描集合中500个元素,再用 srem命令 每次删除一个键
Python代码:
defdel_large_set(): r = redis.StrictRedis(host='redis-host1', port=6379) large_set_key = 'xxx'# 要删除的大set的键名 cursor = '0' whilecursor !=0: cursor, data = r.sscan(large_set_key, cursor=cursor, count=500) foritemindata: r.srem(large_size_key, item) Delete Large List Key删除大的List键,未使用scan命令; 通过 ltrim命令 每次删除少量元素。
Python代码:
defdel_large_list(): r = redis.StrictRedis(host='redis-host1', port=6379) large_list_key = 'xxx'#要删除的大list的键名 whiler.llen(large_list_key)>0: r.ltrim(large_list_key, 0,-101)#每次只删除最右100个元素 Delete Large Sorted set key删除大的有序集合键,和List类似,使用sortedset自带的 zremrangebyrank命令 ,每次删除top 100个元素。
Python代码:
defdel_large_sortedset(): r = redis.StrictRedis(host='large_sortedset_key', port=6379) large_sortedset_key='xxx' whiler.zcard(large_sortedset_key)>0: r.zremrangebyrank(large_sortedset_key,0,99)#时间复杂度更低 , 每次删除O(log(N)+100)